Rohit Tiwari
Rohit Tiwari

Reputation: 822

Best way to set focus on immediate next textbox on page

When I press enter on my current textbox I want to set my focus on the immediate next textbox where ever it would be onthe DOM.

I am not placing any code sample purposely because I dont have any specific scenario. My page loads through an ajax call and the DOM structure would not be known to me.

I am looking for a solution by making use of type[text] and not by using any class or id attribute.

I have been through Link1 Link2 Link3. I also, tried using below code sample:

$('body').on('keypress', 'input[type=text]', function (e) {
    var key = e.which;
    if (key == 13) { // the enter key code
        debugger;
        $(this).closest('.ModalYearItem')
            .next().next().next()
            .find('.TargetMixPercent').focus();

        //  $(this).parents().nextAll('[type=text]').focus()   Approach 2
        //  $(this).parents().siblings()
        //      .find('[type=text]').next(':eq(0)').closest('type=text')    Approach 3
        return false;
    }
})

Upvotes: 1

Views: 110

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

You can use the index of the active focused input and simply move to the next input based on the next index.

Here is a long-hand version to make it obvious:

$(document).on('keypress', 'input[type=text]', function (e) {
    var key = e.which;
    if (key == 13) {
        var $el = $(this);
        var $inputs = $(':input');
        var indx = $inputs.index($el);
        $inputs.eq(indx + 1).focus();
    }
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/mqnthf4n/2/

In jQueryUI you also have a :focusable selector (https://api.jqueryui.com/focusable-selector/) which will include everything that can be focused (including non-input elements!). Otherwise you need to cater for the various types yourself.

Note, this explanatory version does not handle wrapping around at the end, back to the first input, but you can add the range check yourself like this example: http://jsfiddle.net/TrueBlueAussie/mqnthf4n/4/

Note:

  • I changed 'body' to document in the delegated event, as body has bugs (relating to styling) that can mean some events do not bubble to it. Always safer to use document (which is also a fraction faster as it does not need to be parsed). The overhead of one extra element in the bubble chain is negligible.

Upvotes: 2

Alvin Magalona
Alvin Magalona

Reputation: 771

See sample code See http://jsfiddle.net/xalvin11/typw6c8v/

$(':input').each(function (idx) {
    $(this).on('keypress', function (e) {
        if (e.which === 13) {
            var nextInput = $(':input').get(idx + 1);
            if (nextInput)
                nextInput.focus();
        }
    });
});

Upvotes: 0

Related Questions