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:

  1. if type 1 character , let go, background remains white.

  2. 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 of alt or shift type character, still remain white, taking first problem.

  3. 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):

  1. 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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -