Respected All,
I have an HTML form that contains different controls like text boxes and checkboxes. I want to move focus from one control to the next when the user presses the ENTER ke开发者_如何学Cy, without using the tabindex
property.
Is it possible?
You can do this by hooking keypress
and looking for the Enter key, then navigating the DOM to find the next field. Vaguely like this (live copy):
window.onload = function() {
var form,
index;
// Get the form
form = document.getElementById('theForm')
// Hook the keypress event on all its inputs
for (index = 0; index < form.elements.length; ++index) {
hookEvent(form.elements[index], 'keypress', elementKeypressHandler);
}
// Our handler for keypresses
function elementKeypressHandler(event) {
var keyCode,
next,
tryFirst;
// Handle IE/standards variance
event = event || window.event;
// Get the keycode
keyCode = event.keyCode || event.which;
// If Enter...
if (keyCode == 13) {
// Find the next field; if we run out of fields, try
// from the beginning
tryFirst = true;
next = this.nextSibling;
while (next && (next.nodeType != 1 || next.tagName != "INPUT")) {
next = next.nextSibling;
if (!next && tryFirst) {
tryFirst = false;
next = this.parentNode.firstChild;
}
}
// If we have one, focus it
if (next && next !== this) {
next.focus();
}
}
}
// Handle IE vs. standards for DOM2 event hookup
function hookEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on" + event, handler);
}
else {
element["on" + event] = handler;
}
return element;
}
};
Off-topic: This stuff is a lot easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others to iron out browser differences for you and to make it easier to traverse the DOM. For instance, in the above, I've had to account for no fewer than three differences between various browsers, and I've had to use a loop to find the next (or first) element to focus, skipping over non-Element nodes. Libraries will help you avoid writing that repetitive code and focus on what you actually want to do.
you could instead hook into the form's submit event and just focus()
the next input if they weren't on a submit button. less effort if you're not using a 3rd party library.
精彩评论