HTML :
<form>
<fieldset>
<ul>
<li class="answerFields">
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
</li>
</ul>
</fieldset>
</form>
JQUERY :
$('.inputfield input').last().live('focus', function() {
//this is just an example//
document.write('a');
...
});
I have a fiddle.
I want to be able to check if the input that the user focuses is the last input in the <li>
constraints: I cannot change the HTML. The number of inputs will also be increasing or decreasing.
There are two problems in your code:
$('.inputfield input').last().live(...)won’t work..live()has to immediately follow the selector:document.write('a')will replace the current document. But I guess you only have it for testing. Still, you should be usingconsole.logor append to the body.To answer the question:
You can just check whether there are any following
inputelements or not:Alternatively, you could use the following selector if you only want to bind to the last input element:
Make sure you know about the many disadvantages of
.live()[docs]. Consider to use.delegate()[docs] or.on()[docs] instead.You might also want to consider listening to the
focusevent instead ofclick. The focus can be changed with the tab key as well.