有时候会遇到和上面类似的表单字段。我们可以给每个字段限制输入长度,当达到输入长度时自动切换焦点,以增强表单的易用性

Home >Web Front-end >JS Tutorial >The form automatically switches focus when the input length is reached_javascript skills

The form automatically switches focus when the input length is reached_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:53:13984browse
The form automatically switches focus when the input length is reached_javascript skills
Sometimes you will encounter form fields similar to the above. We can limit the input length for each field and automatically switch focus when the input length is reached to enhance the usability of the form
Copy code The code is as follows:


-
-






Copy code The code is as follows:

(function () {
function tabForward(e) {
e = e || window.event;
var target = e.target || e.srcElement;

if (target.value.length === target.maxLength) {
var form = target.form;

for (var i = 0, len = form.elements.length; i < len; i ) {
if (form.elements[i] = == target) {
if (form.elements[i ]) {
form.elements[i ].focus();
}
break;
}
}
}
}

var textbox1 = document.getElementById("txt1");
var textbox2 = document.getElementById("txt2");
var textbox3 = document.getElementById( "txt3");

textbox1.addEventListener("keyup", tabForward, false);
textbox2.addEventListener("keyup", tabForward, false);
textbox3.addEventListener("keyup" , tabForward, false);

})();

The code is actually very simple. It determines whether the length of the input string is equal to the length of the maxLength attribute of the event target. If so, and If there is a next field in the form, it will automatically switch to the next focus.

Let’s briefly talk about the following two attributes:

target.form The form attribute points to the pointer to the form to which the current field belongs. It is read-only.

The form.elements elements attribute is the form A collection of all form elements (fields) in . The elements collection is an ordered list that contains all the fields in the form, such as ,