javascript enter key event code example
Example 1: javascript enter event listener
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
}
});
Example 2: 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 3: javascript key pressed enter
$('.container').on('keydown', 'input', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
e.stopImmediatePropagation();
}
});
Example 4: html button press enter off
Explicit Prevention:
<form>
<label for="name">Name:</label>
<input type="text" name="name" onkeypress="ExplicitPrevention(event)">
<input type="submit" value="Submit">
</form>
<script>
const ExplicitPrevention = function (event) {
var keyPressed = event.keyCode || event.which;
if (keyPressed === 13) {
alert("Test: You pressed the Enter key!!");
event.preventDefault();
}
}
</script>
Example 5: input enter button js
var input = document.getElementById("myInput");
input.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("myBtn").click();
}
})