如何在按键事件之后获得 jQuery.val() ?

我有:

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

现在,警报总是返回 keypress之前的值(例如,字段为空,我键入‘ a’,警报就会给我)。然后我输入‘ b’,警报就会给我‘ a’... ...)。但是我想要 keypress之后的值-我怎么才能做到呢?

背景: 我希望在文本字段包含至少一个字符时立即启用一个按钮。所以我对每个 keypress事件运行这个测试,但是使用返回的 val(),结果总是落后一步。使用 change()事件对我来说不是一个选项,因为那样的话按钮将被禁用,直到您离开文本框。如果有更好的办法,我很高兴听到这个!

87280 次浏览

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.

instead of keypress, use keyup.

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.

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

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