Search code examples
jquerykeypress

Jquery key press is being fired too early


I have a searchbar. If i type something in that searchbar i want to compare the input of the seachbar to the names in my string in real time:

this array contains the word hundai: allRowsArray[0][1];

This is my javascript code:

   jQuery("#carsearchbar").keypress(function(){
    carname = allRowsArray[0][1];
    var searchword = jQuery("#carsearchbar").val();
    jQuery("#logger").text(carname.startsWith(searchword)+"|"+carname +"|"+searchword+"|"+searchword.length+"");
    });

I type h and it immediately outputs:        true|hundai||0|     
If i type hu it immediately  displays:   true|hundai|h|1|  

As you can see the keypess firing is being performed before the number or value is added to the input field. So lets say i want to look for the word hundai in my array i have to type hundai and a space behind it. Or it wil only search "hunda" without the i.

Is there a way around this? Maybe a delay? A delay sounds like bad form.


Solution

  • Use keyup instead of keypress so that you get the current character you just pressed from the val() for that element:

    var allRowsArray = [['someName','hundai']];
    jQuery("#carsearchbar").keyup(function(){
      carname = allRowsArray[0][1];
      var searchword = jQuery("#carsearchbar").val();
      jQuery("#logger").text(carname.startsWith(searchword)+"|"+carname +"|"+searchword+"|"+searchword.length+"");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id='carsearchbar' type-'text' />
    
    <span id='logger'></span>