I have following issue:
I got an event listener on an input field. On every keydown event the value of the input field should get validated. The problem is that the value assigned to the event-target is delayed:
-
You have an empty input field and type down one letter:
$('form.registration').keydown(function(e) { var $el = $(e.target); if ($el.val() == "") { $el.closest("div.control-group").addClass("error"); } console.log($el.val()); // this logs "" }); -
You type in the second letter
$('form.registration').keydown(function(e) { var $el = $(e.target); if ($el.val() == "") { $el.closest("div.control-group").addClass("error"); } console.log($el.val()); // this logs the first letter (for example: "a") });
As you see the value is always delayed by one letter.
How can I fix this?
I will suggest you use
keyupinstead. This will prevent your program running intensively when user presses the key and holds it, the content is being processed only after user releases the key. This method is very convenient in many cases.