javascript - jQuery: Getting new value in keydown handler -
i came across question: onkeypress vs. onkeyup , onkeydown, found keypress
supposed fire whenever character typed text input. trying run following code. supposed make input's background yellow moment text length exceeds 0, or white moment 0. can't make work. if try keydown
, have following problems:
if type 1 character , let go, background remains white.
if then, press
backspace
, clearing 1 character, turns yellow (just opposite of want!). if press other key (alt
,shift
) turn white again. in fact, if instead ofalt
orshift
type character, still remain white, taking first problem.if type press character key , keep pressed, background remains white first character, , turns yellow 2nd character onwards.
if try keyup
only, these problems (as expected):
- the background doesn't change long keys kept pressed, when character added empty input or entire text deleted.
if try keypress
, face same problems keydown
, though supposed work.
if bind 3 handlers keyup
, keydown
, keypress
(god desperate!), problems solved except problem 3 of keydown
: if type press character key , keep pressed, background remains white first character, , turns yellow 2nd character onwards.
how solve 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' />
when keydown event fired, character not yet written input box.
i did research , it's recommended use timeout
in order behaviour want. apparently, during tiny delay, change
event on input fired, , .val()
returns new content.
here's 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 jsfiddle
Comments
Post a Comment