JQuery live keydown not registered until second key press

I am trying to add a class (.active) to a text box as soon as the user starts typing. I got it to work with the following code, but for some reason the .active class does not apply immediately after user input, it only applies after entering the second letter. Any ideas?

$(document).ready(function() { loginField = $('.field'); loginField.live('keydown', function(){ if ($(this).val()){ $(this).addClass('active'); } }); }); 
+4
source share
1 answer

You want keyup here, update based on comments :

 $(document).ready(function() { $('.field').live('keydown', function(){ $(this).addClass('active'); }).live('keyup', function() { $(this).toggleClass('active', $(this).val() != ''); }); }); 

Your .live() starts correctly, but .val() does not change until there is a keyup , keydown fires before the value is updated, so your if() will not be true until the second key is pressed.

+4
source

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


All Articles