Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Last Item in an Array in JavaScript... >>
<< How to Stop setInterval() Call in JavaScript...