Search code examples
javascriptjquerykeypresskeydown

Using keydown() why after first character if alert the value is empty?


If I press (for the first time) a character, than the alert prints an empty value.

How is possible? I don't understand.

$('#search-vulc').on('keydown', function() {
  var textinsert = ($(this).val()).toLowerCase();
  alert(textinsert);
});

Please tell me how I can print it with the first time, when the character is pressed.

Here is there also a jsfiddle example:

https://jsfiddle.net/06xg4c78/1/


Solution

  • Use keuyp event:

    This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added.

    $('#search-vulc').on('keyup', function() {
      var textinsert = ($(this).val()).toLowerCase();
      alert(textinsert);
    });