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

JavascriptJqueryFormsEventsJquery Events

Javascript Problem Overview


I got:

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

Now the alert always returns the value BEFORE the keypress (e.g. the field is empty, I type 'a' and the alert gives me ''. Then I type 'b' and the alert gives me 'a'...). But I want the value AFTER the keypress - how can I do that?

Background: I'd like to enable a button as soon as the text field contains at least one character. So I run this test on every keypress event, but using the returned val() the result is always one step behind. Using the change() event is not an option for me because then the button is disabled until you leave the text box. If there's a better way to do that, I'm glad to hear it!

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

instead of keypress, use keyup.

Solution 4 - Javascript

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.

Solution 5 - Javascript

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));
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJörg BrenninkmeyerView Question on Stackoverflow
Solution 1 - JavascriptHooray Im HelpingView Answer on Stackoverflow
Solution 2 - JavascriptEaten by a GrueView Answer on Stackoverflow
Solution 3 - JavascriptKris van der MastView Answer on Stackoverflow
Solution 4 - JavascriptPointyView Answer on Stackoverflow
Solution 5 - JavascriptDavid OliverosView Answer on Stackoverflow