enter event in javascript code example
Example 1: javascript enter event listener
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for 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: html button press enter off
Explicit Prevention:
<form>
<label for="name">Name:</label>
//Not able to press `Enter`
<input type="text" name="name" onkeypress="ExplicitPrevention(event)">
//Able to press `Enter`
<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>
//Also check: https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
//and: https://www.geeksforgeeks.org/how-to-disable-form-submit-on-enter-button-using-jquery/
Example 4: input enter button js
// Get the input field
var input = document.getElementById("myInput");
input.addEventListener("keyup", (event) => {
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
})
Example 5: evento tecla enter javascript
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});