WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Trigger a Button Click on Enter Key Press in a Text Box in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the click() Method

You can simply use the click() method to simulates a mouse click on an element.

The following example will show you how to trigger a button click on the Enter key press in a text box or input field in JavaScript. Let's try it out and see how it actually works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Trigger a Button Click on Enter Key Press in a Text Input</title>
<script>
    function showHint(){
        document.getElementById("hint").innerHTML += "<p>The Enter key is pressed.</p>"
    }

    document.addEventListener("DOMContentLoaded", function(){
        document.getElementById("myInput").addEventListener("keypress", function(event){
            if(event.keyCode == 13){
                document.getElementById("myBtn").click();
            }
        });
    });
</script>
</head>
<body>   
    <p><strong>Note:</strong>Type anything into the text box below and press the Enter key on the keyboard.</p>
    <p><input type="text" id="myInput"></p>
    <p><button type="button" id="myBtn" onclick="showHint();">My Button</button></p>
    <div id="hint"></div>
</body>
</html>

Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties