Use KeyboardEvent to trigger enter key programmatically in JavaScript. Execute the onkeydown function with dispatchEvent when the user clicks the button.
Example press enter key programmatically in JavaScript
HTML example code.
Trigger an enter keypress event on my input without actually pressing the enter key, more just click on the button.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txtbox" placeholder="trigger enter key press">
<button onclick="enterfun()"> Call Enter</button>
<script>
var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
if (e.key == "Enter") {
alert('enter key pressed');
}
e.preventDefault();
};
function enterfun() {
var ev = new KeyboardEvent('keydown', {altKey:false,
bubbles: true,
cancelBubble: false,
cancelable: true,
charCode: 0,
code: "Enter",
composed: true,
ctrlKey: false,
currentTarget: null,
defaultPrevented: true,
detail: 0,
eventPhase: 0,
isComposing: false,
isTrusted: true,
key: "Enter",
keyCode: 13,
location: 0,
metaKey: false,
repeat: false,
returnValue: false,
shiftKey: false,
type: "keydown",
which: 13});
txtbox.dispatchEvent(ev);
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version