Why is my jQuery keydown feature only working on the first input element
I've built a small jQuery script that adds a class to witch ever input field I'm writing in. However it only works on all input fields after something is written in the first input field, see dev.resihop.nu for example.
Th开发者_如何学Ce code:
$('.field').keydown(function () {
if ($('.field').val() !== 'Ort, gata eller kommun') {
$(this).addClass("focus");
};
});
It's because you're grabbing the elements one more time with $('.field').val()
. Change it to:
$('.field').keydown(function () {
if ($(this).val() !== 'Ort, gata eller kommun') {
$(this).addClass("focus");
};
});
$('.field').val()
returns the value of the first field that matches .field
. You have to use $(this).val()
to get the value of the element that actually fired the event.
精彩评论