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

前端 未结 12 1592
遥遥无期
遥遥无期 2020-11-28 05:12

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

相关标签:
12条回答
  • 2020-11-28 06:03

    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/

    0 讨论(0)
  • 2020-11-28 06:04

    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.

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

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

    0 讨论(0)
  • 2020-11-28 06:04
    <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>
    
    0 讨论(0)
  • 2020-11-28 06:06

    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 keydown and keypress handlers (e.g. backspace and delete keys are suppressed by some browsers).
    2. Handling keydown is 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.

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

    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/

    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.

    0 讨论(0)
  • 2020-11-28 06:07

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

    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.

    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 setTimeout with a timeout of 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/

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

    0 讨论(0)
  • 2020-11-28 06:09

    There is a better way to do this. Use the concat Method. Example

    declare a global variable. this works good on angular 10, just pass it to Vanilla JavaScript. Example:

    HTML

    <input id="edValue" type="text" onKeyPress="edValueKeyPress($event)"><br>
    <span id="lblValue">The text box contains: </span>
    

    CODE

    emptyString = ''
    
    edValueKeyPress ($event){
       this.emptyString = this.emptyString.concat($event.key);
       console.log(this.emptyString);
    }
    
    0 讨论(0)
提交回复
热议问题