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

前端 未结 12 1643
遥遥无期
遥遥无期 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
    慢半拍i (楼主)
    2020-11-28 05:57

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

    This is a little hacky, but doing something like

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

    seems to handle the best of all worlds.

提交回复
热议问题