When the keydown event is fired, the character is not yet written to the input box.
I did some research and it's recommended to use timeout
in order to get the behaviour you want. Apparently, during the tiny delay, a change
event on the input is fired, and .val()
then returns the new content.
Here's a 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 a jsFiddle