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

前端 未结 12 1628
遥遥无期
遥遥无期 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条回答
  •  -上瘾入骨i
    2020-11-28 05:47

    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;
    }

    The text box contains:

    I'd rewrite this a bit, though:

    function showCurrentValue(event)
    {
        const value = event.target.value;
        document.getElementById("lblValue").innerText = value;
    }

    The text box contains:

提交回复
热议问题