简体   繁体   中英

jQuery keypress/keydown not working properly

I have made a live search bar in jQuery but I have a problem!

$(document).on('keydown', '.searchInput', function(){ // or keypress I have the same result
  console.log($(this).val());
});

When I press a button in the input field .searchInput it logs the last value it had. For example, if I type a it will log (empty), then if I type s (so the search bar has as in it) it will log a , then if I type d ( asd in search bar) it will log as and so on. What am I doing wrong? Thank you!

If I understand the question correctly, you are looking to capture the complete value in the text box for which you need to attach keyup event and not keydown.

$(document).on('keyup', '.searchInput', function(){ // or keypress I have the same result
  console.log($(this).val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM