简体   繁体   中英

Why does the “keypress” event handler not fire consistently?

I am having a problem with this function. I cannot get it to fire properly. It does work, but when I highlight the quantity in the form and change the value (the value is initially set to 1), my stock level is 20, when I type in 21 it won't display the message unless I press another key. What am I doing wrong? I have tried every event possible, and can't figure out what I am doing wrong. BTW, this is in a jQuery UI dialog box.

$('#qty').live('keypress', function() {
  $('#response').hide();
  if($('#qty').val() > stockLevel) {
    var response = 'You selected more than we have in stock, we have reset your quantity to the maximum number available in stock';
    $('#qty').val(stockLevel);
    $('#response').html(response).show('blind', {}, '200'); 
    return false;
 }
});

Thanks for you help.

The keypress event has notoriously inconsistent behavior (because it is not defined in any standards). In your case your event is firing before the browser puts the text into the textbox. Use the keyup event instead.

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