I have a text field and a button as shown below. How can I utilize JavaScript to activate the button’s click function when the Enter key is pressed within the text field?
Currently, I have another submit button on the page, so I cannot convert this button into a submit type. I am looking for a solution that triggers this specific button’s action only when the Enter key is pressed inside this text field, without affecting other inputs.
<input type="text" id="searchField" />
<input type="button" id="searchBtn" value="Search" onclick="performAction();" />
To achieve the desired functionality, you can add an event listener for the keydown
event on the text field. Within this event listener, you can check if the Enter
key (key code 13) is pressed. If so, you can programmatically trigger the button’s click event. Here is how you can implement this:
html
<input type=“text” id=“searchField” />
<input type=“button” id=“searchBtn” value=“Search” onclick=“performAction();” />
Now, add the following JavaScript code to handle the Enter
key press:
javascript
document.getElementById(‘searchField’).addEventListener(‘keydown’, function(event) {
if (event.key === ‘Enter’) {
document.getElementById(‘searchBtn’).click();
}
});
This script listens for keydown events on the searchField
input. When the Enter
key is pressed, it calls the click method on searchBtn
, effectively triggering the button’s click event programmatically. This approach ensures that only this specific button is activated without converting any input types or affecting other elements on the page.
You can also use a cleaner approach with HTML5 form
and submit
event to trigger the button without changing its type, by using JavaScript. Here’s how:
<form id="searchForm" onsubmit="return false;">
<input type="text" id="searchField" />
<input type="button" id="searchBtn" value="Search" onclick="performAction();" />
</form>
document.getElementById('searchField').addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // Prevent default form submission
document.getElementById('searchBtn').click();
}
});
This prevents form submission and directly triggers the button when Enter
is pressed in the searchField
. Perfect for handling multiple buttons.