JavaScript > Events

Onkeypress in JavaScript

How to execute a function when key is pressed on the element in JavaScript?


OnKeyPress is a special type of event that executes when user press the key on the element in which it is attached. In case we want to execute a function when key is pressed on the element, we can follow this approach.

Enter your name:
    <input type="text" name="txtName" id="txtName" onkeypress="CallFunction(this.id)" />
    <input type="button" id="btn" name="btn" value="Submit" />
    <p>The text in the textbox is:
        <label id="lblText"></label>
    </p>
    
    <script>
        function CallFunction(id) {
          document.getElementById("lblText").innerHTML = 
document.getElementById(id).value; } </script>

In the above code snippet, we have specified onkeypress event on the textbox that calls “CallFunction()” function. In this function, we are setting the html label text to the textbox value.

OUTPUT

Important: 

(In this case, you may notice that the last character is not appearing in the html label, this is because of the behaviour of onkeypress event. In order to get exact value of the textbox, use onkyeup event, it works exactly same as onkeypress. Just replace onkeypress to onkeyup.)

 Views: 1105 | Post Order: 41



Write for us