keycode for enter button in javascript code example
Example 1: hit enter button lick in js
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
Example 2: javascript bind key to button
$(document).keypress(function(e){
if (e.which == 13){
$("#button").click();
}
});
window.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
alert('enter was pressed!');
}
});
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
Example 3: input enter button js
var input = document.getElementById("myInput");
input.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("myBtn").click();
}
})
Example 4: enter keycode
Enter = keyCode 13
Space = keyCode 32