jQuery find next form Element for navigation (some fields dynamically added to form)
I want to shift navigation from tab key to Enter key. For that I hooked keypress event of the form like
$("form").live("keypress", function (e) {
if (e.keyCode == 13) {
//here should come the code for finding next element and focusing it
return false; // this line prevents submission of form on enter key
}
In this function I just have to find next form element and shift focus on that one. To get next form element I used selector from this answer. But there are couple of problems with it:
- it does not cater for select lists and any ot开发者_开发问答her elements than input.
- it does not cater for hidden, disabled and readonly inputs
Besides this it uses index property of inputs to find next elements but the problem is when I alert all form elements with their indexes. they are not unique.
$('form input,form select').each(function (ind, elem) {
alert($(elem).attr("name"));
alert($(elem).index());
});
There are many form elements with 0 index. It is notable that some form elements are inserted in the DOM using JavaScript i.e after page load. How can I solve this problem?
Something like this? You may have to tinker with the isFocusableInput
function to get the desired effect. I've left the console.log
s in so you can see what's happening.
$("form").live("keypress", function (e) {
function isFocusableInput(el) {
// TODO - e.g.
var $el = $(el);
var typeOk = !el.type || !el.type.match(/^(hidden)$/);
return $el.is(":visible") && typeOk && !$el.is('[readonly]') && !$el.is('[disabled]');
}
function findFocusableInput($form, $input) {
var inputs = $form.find(":input");
console.log(inputs);
var thisIdx = inputs.index($input);
console.log("thisIdx=" + thisIdx);
var count = 0;
var input = null;
// -1 because we don't want to focus the original element
while (++count < inputs.length-1) {
var i = (thisIdx+count)%inputs.length;
input = inputs.eq(i)[0];
console.log(i + "," + input.tagName);
console.log(input);
if (isFocusableInput(input)) {
return input;
}
}
return null;
}
var $input = $(e.target);
var $form = $(this);
console.log($input);
console.log($form);
if (e.keyCode == 13) {
e.stopPropagation();
var focusableInput = findFocusableInput($form, $input);
console.log(focusableInput);
if (focusableInput) {
focusableInput.focus();
}
return false;
}
});
i was able to accomplish this task using following code
$("form").live("keypress", function (e) {
if (e.keyCode == 13) {
var $fomrElements = $('form input,form select').not(":hidden").not(":disabled");
var $nextIndex = $fomrElements.index(e.target) + 1;
var $nextInput = $fomrElements.eq($nextIndex);
$nextInput.focus();
return false;
}
});
精彩评论