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' />
source share