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

后端 未结 6 1737
北荒
北荒 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: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.

提交回复
热议问题