Как получить текст вводимого текстового поля во время onKeyPress?

Я пытаюсь получить текст в текстовом поле, как пользователь вводит в него (детская площадка):

function edValueKeyPress() {
    var edValue = document.getElementById("edValue");
    var s = edValue.value;

    var lblValue = document.getElementById("lblValue");
    lblValue.innerText = "The text box contains: " + s;

    //var s = $("#edValue").val();
    //$("#lblValue").text(s);    
}
<input id="edValue" type="text" onKeyPress="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>

& # X200B; Код выполняется без ошибок, за исключением того, чтоvalue изinput text коробка, во времяonKeyPress всегда значениеbefore изменение:

enter image description here

Question: How do I get the text of a text box during onKeyPress?

Bonus Chatter

Есть три события, связанные с"the user is typing" в HTML DOM:

onKeyDown onKeyPress onKeyUp

ВWindows, получатель чего-тоWM_Key сообщения становятся важными, когда пользователь удерживает нажатой клавишу, и клавиша начинает повторяться:

WM_KEYDOWN('a') - user has pushed down the A key WM_CHAR('a') - an a character has been received from the user WM_CHAR('a') - an a character has been received from the user WM_CHAR('a') - an a character has been received from the user WM_CHAR('a') - an a character has been received from the user WM_CHAR('a') - an a character has been received from the user WM_KEYUP('a') - the user has released the A key

В результате в текстовом элементе управления появятся пять символов:aaaaa

Важным моментом является то, что вы реагируете наWM_CHAR сообщение, которое повторяется. В противном случае вы пропустите события, когда клавиша нажата.

ВHTML все немного по-другому:

onKeyDown onKeyPress onKeyDown onKeyPress onKeyDown onKeyPress onKeyDown onKeyPress onKeyDown onKeyPress onKeyUp

HTML доставляетKeyDown а такжеKeyPress каждый ключ повторяется. ИKeyUp Событие возникает только тогда, когда пользователь отпускает ключ.

Take aways

I can respond to onKeyDown or onKeyPress, but both are still raised before the input.value has been updated I cannot respond to onKeyUp, because it doesn't happen as the text in the text-box changes.

Question: Как получить текст текстового поля во времяonKeyPress?

Bonus Reading Getting a form value with jQuery Get the value in an input text box

Ответы на вопрос(11)

Ваш ответ на вопрос