I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?
There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.
<input type="text" id="txtSearch" /> <input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
You don't need to use JavaScript to do submit button or input on entering key pressed. Just need to mark it up with type="submit" , and the other buttons mark them with type="button" .
You can execute a function by pressing the enter key in a field using the key event in JavaScript. If the user presses the button use the keydown to get know its enter button or not. If it enters the key then call the JavaScript function.
In jQuery, the following would work:
$("#id_of_textbox").keyup(function(event) { if (event.keyCode === 13) { $("#id_of_button").click(); } });
$("#pw").keyup(function(event) { if (event.keyCode === 13) { $("#myButton").click(); } }); $("#myButton").click(function() { alert("Button code executed."); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password: <input id="pw" type="password"><br> <button id="myButton">Submit</button>
Or in plain JavaScript, the following would work:
document.getElementById("id_of_textbox") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("id_of_button").click(); } });
document.getElementById("pw") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("myButton").click(); } }); function buttonCode() { alert("Button code executed."); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Username:<input id="username" type="text"><br> Password: <input id="pw" type="password"><br> <button id="myButton" onclick="buttonCode()">Submit</button>
Then just code it in!
<input type = "text" id = "txtSearch" onkeydown = "if (event.keyCode == 13) document.getElementById('btnSearch').click()" /> <input type = "button" id = "btnSearch" value = "Search" onclick = "doSomething();" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With