简体   繁体   中英

using is(':last') to check the last element

I have a list of input elements. I want to bind a keyup event handler to them, so that whenever user hits Enter , he goes to the next field. But if the input is the last input, then I want to fire the click event of a button, so that user goes to another level. My code is like this:

$('.loginBody input:visible').keyup(function (e) {
    if (e.keyCode == 13) {
        if ($(this).is(':last')) {
            $('#next').click();
        }
        else {
            $(this).closest('input').focus();
        }
    }
});

However, seems that is(':last') doesn't work. What's wrong?

:last returns the last element of a collection , and $(this) is only a single element collection.

Try using the :last-child selector instead, which will check whether your <input> is really the last one in that group.

Alternatively, if your fields aren't all in the same parent, reverse the sense of your test:

if ($('input').filter(':last').is(this)) {
    // this is the last input
}

NB: using .filter(':last') rather than input:last per recommendations at http://api.jquery.com/last-selector/

UPDATED: You could create two different bindings:

$('.loginBody input:last').keyup(function (e) {
    if (e.which == 13) {
             $("#result").html("last one");
        }
    });

$('.loginBody input').not(":last").keyup(function (e) {
    if (e.which == 13) {
             $("#result").html("not last one");
        }
});

Here is a working example: http://jsfiddle.net/6gYXk/1/

have you tried is(':last-child') pseudoclass instead?

:last-child means "if this element is the last child of its parent". Note that only element nodes (HTML tags) count, these pseudo-classes ignore text nodes.

edit: also to focus closest sibling element use:

 $(e.target).next('input').focus();

so full code can be:

$('.loginBody input:visible').keyup(function (e) {
    if (e.keyCode == 13) {
        if ($(this).is(':last-child')) {
            $('#next').click();
        } else {
             $(e.target).next('input').focus();
        }
    }
});

i've prepared an example at: http://jsfiddle.net/HhvUF/

The nicest solution might well be to use nextAll to see if there are any subsequent sibling elements:

if ($(this).nextAll().length) {
    $(this).closest('input').focus();
} else {
    $('#next').click();
}

NB that I have turned the if around to make it easier to read.

If you need to check only for input elements, you can supply a selector:

if ($(this).nextAll('input').length) {

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