Himmators
Himmators

Reputation: 15016

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.

The code:

$('.field').keydown(function () {
  if ($('.field').val() !== 'Ort, gata eller kommun') {  
    $(this).addClass("focus");
  };
});

Upvotes: 3

Views: 458

Answers (2)

Benjamin Wohlwend
Benjamin Wohlwend

Reputation: 31868

$('.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.

Upvotes: 3

Gert Grenander
Gert Grenander

Reputation: 17104

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");
  };
});

Upvotes: 8

Related Questions