How to get text of an input text box during onKeyP

2019-01-10 10:21发布

I am trying to get the text in a text box as the user types in it (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 value of the input text box, during onKeyPress is always the value before the change:

enter image description here

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

Bonus Chatter

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

  • onKeyDown
  • onKeyPress
  • onKeyUp

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

  • 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

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

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

In HTML things are slightly different:

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

Html delivers an KeyDown and KeyPress every key repeat. And the KeyUp event is only raised when the user releases the key.

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: How do I get the text of a text-box during onKeyPress?

Bonus Reading

11条回答
三岁会撩人
2楼-- · 2019-01-10 10:56

Handling the input event is a consistent solution: it is supported for textarea and input elements in all contemporary browsers and it fires exactly when you need it:

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 edValueKeyPress(event)
{
    var value = event.target.value;
    document.getElementById("lblValue").innerText = value;
}
<input id="edValue" type="text" onInput="edValueKeyPress(event)"><br>
The text box contains: <span id="lblValue"></span>

查看更多
男人必须洒脱
3楼-- · 2019-01-10 10:56
<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>
查看更多
贼婆χ
4楼-- · 2019-01-10 10:56

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

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()" />

查看更多
叛逆
5楼-- · 2019-01-10 10:59

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.

Recent JS example

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

//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.]

查看更多
小情绪 Triste *
6楼-- · 2019-01-10 11:02

Try to concatenate the event charCode to the value you get. here is a sample of my code.

<input type="text" name="price" onkeypress="return (cnum(event,this))" maxlength="10"> <p id="demo"></p>

js:

function cnum(event, str) {
    var a = event.charCode;
    var ab = str.value + String.fromCharCode(a);
    document.getElementById('demo').innerHTML = ab;
}

The value in ab will get the latest value in the input field.

查看更多
老娘就宠你
7楼-- · 2019-01-10 11:08

Keep it simple. Use both onKeyPress() and 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/

查看更多
登录 后发表回答