Detecting “value” of input text field after a keydown event in the text field?

后端 未结 6 762
死守一世寂寞
死守一世寂寞 2020-12-08 08:04

So my site has an input box, which has a onkeydown event that merely alerts the value of the input box.

Unfortunately the value of the input does not include the ch

相关标签:
6条回答
  • 2020-12-08 08:36

    Please, try to use oninput event. Unlike onkeydown, onkeypress events this event updates control's value property.

    <input id="txt1" value="cow" oninput="alert(this.value);" />
    
    0 讨论(0)
  • 2020-12-08 08:37

    Note that in newer browsers you'll be able to use the new HTML5 "input" event (https://developer.mozilla.org/en-US/docs/DOM/window.oninput) for this. Most non-IE browsers have supported this event for a long time (see compatibility table in the link); for IE it's version >/9 only unfortunately.

    0 讨论(0)
  • 2020-12-08 08:37

    Jquery is the optimal way of doing this. Please reference the following below:

    let fieldText = $('#id');
    let fieldVal = fieldText.val();
    
    fieldText.on('keydown', function() {
       fieldVal.val();
    });
    
    0 讨论(0)
  • 2020-12-08 08:45

    The event handler only sees the content before the change is applied, because the mousedown and input events give you a chance to block the event before it gets to the field.

    You can work around this limitation by giving the browser a chance to update the field's contents before grabbing its value - the simplest way is to use a small timeout before checking the value.

    A minimal example is:

    <input id="e"
        onkeydown="window.setTimeout( function(){ alert(e.value) }, 1)"
        type="text" value="cow" />
    

    This sets a 1ms timeout that should happen after the keypress and keydown handlers have let the control change its value. If your monitor is refreshing at 60fps then you've got 16ms of wiggle room before it lags 2 frames.


    A more complete example (which doesn't rely on named access on the Window object would look like:

    var e = document.getElementById('e');
    var out = document.getElementById('out');
    
    e.addEventListener('input', function(event) {
      window.setTimeout(function() {
        out.value = event.target.value;
      }, 1);
    });
    <input type="text" id="e" value="cow">
    <input type="text" id="out" readonly>

    When you run the above snippet, try some of the following:

    • Put the cursor at the start and type
    • Paste some content in the middle of the text box
    • Select a bunch of text and type to replace it
    0 讨论(0)
  • 2020-12-08 08:45

    To my knowledge you can't do that with a standard input control unless you roll your own.

    0 讨论(0)
  • 2020-12-08 08:47

    keyup/down events are handled differently in different browsers. The simple solution is to use a library like mootools, which will make them behave the same, deal with propagation and bubbling, and give you a standard "this" in the callback.

    0 讨论(0)
提交回复
热议问题