Why is my keydown jQuery function only working with the first input element

I built a small jQuery script that adds a class for every input field I write in. However, it only works in 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");
  };
});
+3
source share
2 answers

This is because you capture elements again using $('.field').val(). Change it to:

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

$('.field').val() , .field. $(this).val(), , .

+3

Source: https://habr.com/ru/post/1759797/


All Articles