JQuery: getting new value in keydown handler

I came across this question: onKeyPress Vs. onKeyUp and onKeyDown , from where I found that keypress should fire whenever a character is entered into text input. I am trying to run this following code. It is assumed that the input background will be yellow if its text length exceeds 0, or a white moment when it is 0. I cannot make it work. If I try to execute keydown , I have the following problems:

  • If I just type one character and let go, the background remains white.

  • If then, I backspace , thereby clearing one character, it turns yellow (just the opposite of what I want!). If I press any other key ( Alt , Shift ) now, it will turn white again. In fact, if instead of Alt or Shift I type a character, it will still remain white, returning us to the first problem.

  • If I press and hold the symbol key, the background remains white for the first character and then becomes the yellow second character.

If I try only keyup , these are problems (as expected):

  • The background does not change while the keys are pressed, even when a character is added to an empty input or all text is deleted.

If I try keypress , I will encounter the same problems as keydown , although it should work.

If I attach 3 handlers for keyup , keydown and keypress (God is in despair!), Almost all problems are solved, except for problem 3 from keydown : if I type, press the symbol key and save it, the background remains white for the first character, and then becomes the yellow second character.

How to solve this problem?

JS:

 $(document).ready(function() { $("input").bind("keydown", function() { if ($(this).val().length == 0) { $(this).css('background', 'white'); } else { $(this).css('background', 'yellow'); } }); $("input").bind("keypress", function() { if ($(this).val().length == 0) { $(this).css('background', 'white'); } else { $(this).css('background', 'yellow'); } }); $("input").bind("keyup", function() { if ($(this).val().length == 0) { $(this).css('background', 'white'); } else { $(this).css('background', 'yellow'); } }); }); 

HTML:

 <input type='text' /> 
+6
source share
1 answer

When the keydown event is fired, the character is not yet written to the input field.

I did some research and recommended using timeout to get the right behavior. Apparently, during a tiny delay, the change event on the input fires, and .val() then returns the new content.

Here's the working code:

 $(document).ready(function () { var field = $("input"); field.on("keydown", function (e) { setTimeout(function () { if (field.val().length == 0) { field.css('background', 'white'); } else { field.css('background', 'yellow'); } }, 1); }); }); 

Accompanied by jsFiddle

+10
source

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


All Articles