Javascript 如何在onKeyPress期间获取输入文本框的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11365686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:38:30  来源:igfitidea点击:

How to get text of an input text box during onKeyPress?

javascripthtmlinputonkeypress

提问by Ian Boyd

I am trying to get the text in a text box as the user types in it (jsfiddle playground):

我试图在用户输入文本框中获取文本(jsfiddle playground):

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>

? The code runs without errors, except that the valueof the input textbox, during onKeyPressis always the value beforethe change:

? 代码运行没有错误,但该的中input text框,期间onKeyPress总是值之前的变化:

enter image description here

在此处输入图片说明

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

问题:如何在 期间获取文本框的文本onKeyPress

Bonus Chatter

奖金喋喋不休

There are three events related to "the user is typing"in the HTML DOM:

HTML DOM 中有三个与“用户正在输入”相关的事件:

  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onKeyDown
  • onKeyPress
  • onKeyUp

In Windows, the order of WM_Keymessages becomes important when the user holds down a key, and the key begins to repeat:

Windows 中WM_Key当用户按住某个键并且该键开始重复时,消息的顺序变得很重要:

  • WM_KEYDOWN('a')- user has pushed down the Akey
  • WM_CHAR('a')- an acharacter has been received from the user
  • WM_CHAR('a')- an acharacter has been received from the user
  • WM_CHAR('a')- an acharacter has been received from the user
  • WM_CHAR('a')- an acharacter has been received from the user
  • WM_CHAR('a')- an acharacter has been received from the user
  • WM_KEYUP('a')- the user has released the Akey
  • WM_KEYDOWN('a')- 用户按下了A
  • WM_CHAR('a')-a从用户那里收到一个字符
  • WM_CHAR('a')-a从用户那里收到一个字符
  • WM_CHAR('a')-a从用户那里收到一个字符
  • WM_CHAR('a')-a从用户那里收到一个字符
  • WM_CHAR('a')-a从用户那里收到一个字符
  • WM_KEYUP('a')- 用户已释放A密钥

Will result in five characters appearing in a text control: aaaaa

将导致文本控件中出现五个字符: aaaaa

The important point being that the you respond to the WM_CHARmessage, the one that repeats. Otherwise you miss events when a key is pressed.

重要的一点是,您对WM_CHAR消息做出回应,重复的消息。否则,您会在按下某个键时错过事件。

In HTMLthings are slightly different:

HTML 中,情况略有不同:

  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyDown
  • onKeyPress
  • onKeyUp

Html delivers an KeyDownand KeyPressevery key repeat. And the KeyUpevent is only raised when the user releases the key.

Html 提供一个KeyDownKeyPress每个键重复。并且KeyUp只有在用户释放按键时才会引发该事件。

Take aways

带走

  • I canrespond to onKeyDownor onKeyPress, but both are still raised before the input.valuehas been updated
  • I cannot respond to onKeyUp, because it doesn't happen as the text in the text-box changes.
  • 可以回复onKeyDownonKeyPress,但input.value在更新之前两者仍然被提出
  • 我无法响应onKeyUp,因为它不会随着文本框中的文本发生变化而发生。

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

问题:如何在 期间获取文本框的文本onKeyPress

Bonus Reading

奖励阅读

采纳答案by YakovL

Handling the inputevent is a consistent solution: it is supportedfor textareaand inputelements in all contemporary browsers and it fires exactlywhen you need it:

处理该input事件是一致的解决方案:它支持用于textareainput所有现代浏览器元素和它触发正是当你需要它:

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

    var lblValue = document.getElementById("lblValue");
    lblValue.innerText = "The text box contains: " + s;
}
<input id="edValue" type="text" onInput="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>

I'd rewrite this a bit, though:

不过,我会稍微重写一下:

function showCurrentValue(event)
{
    const value = event.target.value;
    document.getElementById("lblValue").innerText = value;
}
<input id="edValue" type="text" onInput="showCurrentValue(event)"><br>
The text box contains: <span id="lblValue"></span>

回答by Jonathan M

Keep it simple. Use both onKeyPress()and onKeyUp():

把事情简单化。同时使用onKeyPress()onKeyUp()

<input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()">

This takes care of getting the most updated string value (after key up) and also updates if the user holds down a key.

这负责获取最新的字符串值(在按键之后),并且如果用户按住某个键也会更新。

jsfiddle: http://jsfiddle.net/VDd6C/8/

jsfiddle:http: //jsfiddle.net/VDD6C/8/

回答by Arnaud Le Blanc

the value of the input text box, during onKeyPress is always the value before the change

输入文本框的值,在 onKeyPress 期间始终是更改前的值

This is on purpose: This allows the event listener to cancel the keypress.

这是故意的:这允许事件侦听器取消按键。

If the event listeners cancels the event, the value is not updated. If the event is not canceled, the value is updated, but after the event listener was called.

如果事件侦听器取消 event,则不会更新该值。如果事件未取消,则更新值,但在调用事件侦听器之后

To get the value after the field value has been updated, schedule a function to run on the next event loop. The usual way to do this is to call setTimeoutwith a timeout of 0:

要在字段值更新后获取值,请安排一个函数在下一个事件循环中运行。执行此操作的通常方法是setTimeout使用超时时间调用0

$('#field').keyup(function() {
    var $field = $(this);

    // this is the value before the keypress
    var beforeVal = $field.val();

    setTimeout(function() {

        // this is the value after the keypress
        var afterVal = $field.val();
    }, 0);
});

Try here: http://jsfiddle.net/Q57gY/2/

在这里试试:http: //jsfiddle.net/Q57gY/2/

Edit: Some browsers (e.g. Chrome) do not trigger keypress events for backspace; changed keypress to keyup in code.

编辑:某些浏览器(例如 Chrome)不会触发退格键事件;在代码中将 keypress 更改为 keyup。

回答by Wajahath

keep it Compact.
Each time you press a key, the function edValueKeyPress()is called.
You've also declared and initialized some variables in that function - which slow down the process and requires more CPU and memory as well.
You can simply use this code - derived from simple substitution.

保持紧凑。
每次按下一个键,edValueKeyPress()都会调用该函数。
您还在该函数中声明并初始化了一些变量 - 这会减慢进程并需要更多的 CPU 和内存。
您可以简单地使用此代码 - 源自简单替换。

function edValueKeyPress()
{
    document.getElementById("lblValue").innerText =""+document.getElementById("edValue").value;
}

That's all you want, and it's faster!

这就是您想要的,而且速度更快!

回答by raksh pal

<asp:TextBox ID="txtMobile" runat="server" CssClass="form-control" style="width:92%;  margin:0px 5px 0px 5px;" onkeypress="javascript:return isNumberKey(event);" MaxLength="12"></asp:TextBox>

<script>
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
</script>

回答by CubicleSoft

None of the answers so far offer a complete solution. There are quite a few issues to address:

到目前为止,没有一个答案提供完整的解决方案。有很多问题需要解决:

  1. Not all keypresses are passed onto keydownand keypresshandlers (e.g. backspace and delete keys are suppressed by some browsers).
  2. Handling keydownis not a good idea. There are situations where a keydown does NOT result in a keypress!
  3. setTimeout()style solutions get delayed under Google Chrome/Blink web browsers until the user stops typing.
  4. Mouse and touch events may be used to perform actions such as cut, copy, and paste. Those events will not trigger keyboard events.
  5. The browser, depending on the input method, may not deliver notification that the element has changed until the user navigates away from the field.
  1. 并非所有按键都传递给keydownkeypress处理程序(例如退格键和删除键被某些浏览器抑制)。
  2. 处理keydown不是一个好主意。在某些情况下,按键不会导致按键!
  3. setTimeout()样式解决方案在 Google Chrome/Blink 网络浏览器下会延迟,直到用户停止输入。
  4. 鼠标和触摸事件可用于执行诸如剪切、复制和粘贴之类的操作。这些事件不会触发键盘事件。
  5. 根据输入法的不同,浏览器可能不会传递元素已更改的通知,直到用户导航离开该字段。

A more correct solution will handle the keypress, keyup, input, and changeevents.

更正确的解决方案将处理keypresskeyupinput,和change事件。

Example:

例子:

<p><input id="editvalue" type="text"></p>
<p>The text box contains: <span id="labelvalue"></span></p>

<script>
function UpdateDisplay()
{
    var inputelem = document.getElementById("editvalue");
    var s = inputelem.value;

    var labelelem = document.getElementById("labelvalue");
    labelelem.innerText = s;
}

// Initial update.
UpdateDisplay();

// Register event handlers.
var inputelem = document.getElementById("editvalue");
inputelem.addEventListener('keypress', UpdateDisplay);
inputelem.addEventListener('keyup', UpdateDisplay);
inputelem.addEventListener('input', UpdateDisplay);
inputelem.addEventListener('change', UpdateDisplay);
</script>

Fiddle:

小提琴:

http://jsfiddle.net/VDd6C/2175/

http://jsfiddle.net/VDDd6C/2175/

Handling all four events catches all of the edge cases. When working with input from a user, all types of input methods should be considered and cross-browser and cross-device functionality should be verified. The above code has been tested in Firefox, Edge, and Chrome on desktop as well as the mobile devices I own.

处理所有四个事件可捕获所有边缘情况。在处理来自用户的输入时,应考虑所有类型的输入法,并应验证跨浏览器和跨设备的功能。上面的代码已经在 Firefox、Edge 和 Chrome 桌面以及我拥有的移动设备上进行了测试。

回答by vibs2006

By using event.keywe can get values prior entry into HTML Input Text Box. Here is the code.

通过使用event.key,我们可以在进入 HTML 输入文本框之前获取值。这是代码。

function checkText()
{
  console.log("Value Entered which was prevented was - " + event.key);
  
  //Following will prevent displaying value on textbox
  //You need to use your validation functions here and return value true or false.
  return false;
}
<input type="text" placeholder="Enter Value" onkeypress="return checkText()" />

回答by dx_over_dt

So there are advantages and disadvantages to each event. The events onkeypressand onkeydowndon't retrieve the latest value, and onkeypressdoesn't fire for non-printable characters in some browsers. The onkeyupevent doesn't detect when a key is held down for multiple characters.

所以每个事件都有优点和缺点。事件onkeypressonkeydown不会检索最新值,并且onkeypress不会在某些浏览器中为不可打印的字符触发。该onkeyup事件不会检测何时按下多个字符的键。

This is a little hacky, but doing something like

这有点hacky,但做类似的事情

function edValueKeyDown(input) {
    var s = input.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" onkeydown="setTimeout(edValueKeyDown, 0, this)" />

seems to handle the best of all worlds.

似乎处理所有世界中最好的。

回答by Utkanos

I normally concatenate the field's value (i.e. before it's updated) with the key associated with the key event. The following uses recent JS so would need adjusting for support in older IE's.

我通常将字段的值(即在更新之前)与与键事件关联的键连接起来。以下使用最新的 JS,因此需要调整以支持较旧的 IE。

Recent JS example

最近的 JS 示例

document.querySelector('#test').addEventListener('keypress', function(evt) {
    var real_val = this.value + String.fromCharCode(evt.which);
    if (evt.which == 8) real_val = real_val.substr(0, real_val.length - 2);
    alert(real_val);
}, false);

Support for older IEs example

支持较旧的 IE 示例

//get field
var field = document.getElementById('test');

//bind, somehow
if (window.addEventListener)
    field.addEventListener('keypress', keypress_cb, false);
else
    field.attachEvent('onkeypress', keypress_cb);

//callback
function keypress_cb(evt) {
    evt = evt || window.event;
    var code = evt.which || evt.keyCode,
        real_val = this.value + String.fromCharCode(code);
    if (code == 8) real_val = real_val.substr(0, real_val.length - 2);
}

[EDIT - this approach, by default, disables key presses for things like back space, CTRL+A. The code above accommodates for the former, but would need further tinkering to allow for the latter, and a few other eventualities. See Ian Boyd's comment below.]

[编辑 - 默认情况下,这种方法会禁用诸如退格、CTRL+A 之类的按键。上面的代码适用于前者,但需要进一步修改以允许后者以及其他一些可能性。请参阅下面的伊恩·博伊德 (Ian Boyd) 的评论。]

回答by Charles Bretana

easy...

简单...

In your keyPress event handler, write

在您的 keyPress 事件处理程序中,写入

void ValidateKeyPressHandler(object sender, KeyPressEventArgs e)
{
    var tb = sender as TextBox;
    var startPos = tb.SelectionStart;
    var selLen= tb.SelectionLength;

    var afterEditValue = tb.Text.Remove(startPos, selLen)
                .Insert(startPos, e.KeyChar.ToString()); 
    //  ... more here
}