Search code examples
javascriptjquerystringinputkeypress

Simple keypress event not working correctly on jquery


My code works but only returns true if I write again after the string that exists. where flowName is a text input.

For example: Database: Flow123

on keypress: Flow123 returns false but when i click in another key it returns true.

This is my code:

//validate flow name
$('#flowName').keypress(function () {
   var flowName = $(this).val();
   $.ajax({
       url: '/check-flowName',
       type: 'post',
       data: {flowName: flowName},
       success: function (result) {
           console.log(result);
           //if exists
           if (result) {

           }
           //else do nothing
       }
   })
});

How do I fix this?


Solution

  • If you use keypress you will loose the last pressed key in the value of your input, because the event is fired when the key is pressed, so it doesn't take this key into consideration in the input value.

    Solution:

    You will need to use keyup event, so the last pressed key can be considered into the value when the key is released.

    Just replace the keypress with keyup in your code:

    $('#flowName').keyup(function () {
       var flowName = $(this).val();
    
    });