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?
:lastreturns the last element of a collection, and$(this)is only a single element collection.Try using the
:last-childselector 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:
NB: using
.filter(':last')rather thaninput:lastper recommendations at http://api.jquery.com/last-selector/