简体   繁体   中英

jquery find next element without attribute

I have a large form that I want to navigate through by pressing enter instead of tab. I have a simple script which worked fine until I added some disabled fields into the mix. How can I skip the fields that have the attribute of disabled?

I've tried using a loop but I cannot get it to skip the two disabled fields together and focus to the next one, as it seems to stay on the field before the disabled ones.

Failing that, is there a way to replace the enter keyCode of 13 with the one for tab? I've tried a few solutions here but none of them seem to work

$('input').on('keydown', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $('input')[$('input').index(this)+1].focus();
    }
});

You can use the :enabled selector .

$('input').on('keydown', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        $('input:enabled')[$('input:enabled').index(this)+1].focus();
    }
});

JSFiddle

You can just filter the collection and remove the disabled inputs, and caching the selectors saves you three DOM lookups.

Note that there is a slight difference between :enabled and .not([disabled]) , the former selects elements that have their boolean disabled property strictly equal to false, while the latter selects elements that do not have a disabled attribute set (regardless of its value).

var inputs = $('input');

inputs.on('keydown', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();

        var enabled = inputs.not('[disabled]');

        enabled.eq( enabled.index(this) + 1 ).focus();
    }
});
<input />
<input />
<input disabled="disabled"/>
<input />

$('input').on('keydown', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        var enabledInput = $('input').not('[disabled]');
        enabledInput.eq( enabledInput.index(this) + 1 ).focus();        
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM