How can I get jquery .val() AFTER keypress event?

后端 未结 6 1638
北荒
北荒 2020-11-28 06:32

I got:

$(someTextInputField).keypress(function() {
  alert($(this).val());
});

Now the alert always returns the value BEFORE the keypress (

相关标签:
6条回答
  • 2020-11-28 07:16

    Change keypress to keyup:

    $(someTextInputField).on("keyup", function() {
      alert($(this).val());
    });
    

    keypress is fired when the key is pressed down, keyup is fired when the key is released.

    0 讨论(0)
  • 2020-11-28 07:17

    instead of keypress, use keyup.

    0 讨论(0)
  • 2020-11-28 07:19

    Try something like this:

    $('#someField').keypress(function() {
      setTimeout(function() {
        if ($('#someField').val().length > 0)
          $('#theButton').attr('disabled', false);
      }, 1);
    });
    

    That simply introduces a timeout so that after the "keypress" event loop completes, your code will run almost immediately thereafter. Such a short timer interval (even if rounded up by the browser) will not be noticeable.

    edit — or you could use "keyup" like everybody else says, though its semantics are different.

    0 讨论(0)
  • 2020-11-28 07:25

    You may want to hook up an onchange event handler instead of using any of the key events.

    $(someTextInputField).change(function() {
        alert($(this).val());
    });
    

    Using Edit > Paste or a Right-Click then Paste will fire a change event, but not a key event. Note some browsers may simulate a key event on a paste (though I don't know of any) but you can't count on that behavior.

    0 讨论(0)
  • 2020-11-28 07:32

    Alternatively, you can use the keydown event with a timeout of 0.

    That way, the changes will be applied instantly, instead of being applied when the user stops holding the key.

    $(someTextInputField).on("keydown", function() {
      setTimeout(function($elem){
        alert($elem.val());
      }, 0, $(this));
    });
    
    0 讨论(0)
  • 2020-11-28 07:35

    Surprised that no one mentioned the js "input" event:

    $(someTextInputField).on('input', function() {
      alert($(this).val());
    });
    

    Recommended.

    https://developer.mozilla.org/en-US/docs/Web/Events/input

    0 讨论(0)
提交回复
热议问题