Tab behavior using jQuery

2019-03-06 03:12发布

问题:

I have a some text boxes in my form. I don't know their id values. I want change the cursor position from the existing one to the next field by pressing Enter.
Pay attention that the cursor may be in different positions at the first time.

What is your suggestion?

回答1:

you didn't provide your markup so I can't make assumption about your structure (e.g. using .next() if they are sibling elements). So, supposing you have input text, try this example (for jQuery 1.7+)

$(document).ready(function() {

    var inputs = $('input[type="text"]');
    var len = inputs.length;

    inputs.on('keyup', function(evt) {
        if (evt.keyCode === 13) {
           var currentInput = inputs.index($(this));
           inputs.eq((currentInput < len - 1)
                     ? currentInput + 1
                     : 0).focus();

           evt.preventDefault();
        }
    });
});

When you press enter on last input, the first input will be focused (in a loop). See a jsfiddle example: http://jsfiddle.net/8ruDV/