Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to fire after pressing ENTER in text input with HTML?
There are several ways to detect when the ENTER key is pressed in a text input field. Here are the most common and effective approaches.
Using jQuery with Custom Event
This approach creates a custom "enterKey" event that triggers when ENTER is pressed:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input').bind("enterKey",function(e){
alert("Enter key pressed");
});
$('input').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
});
</script>
</head>
<body>
<input type="text">
<p>Press Enter key in the above input text.</p>
</body>
</html>
Using Vanilla JavaScript with keydown Event
A modern approach without jQuery dependencies:
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function() {
const input = document.querySelector('input');
input.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
alert('Enter key pressed!');
console.log('Input value:', this.value);
}
});
});
</script>
</head>
<body>
<input type="text" placeholder="Type and press Enter">
<p>Press Enter key in the above input text.</p>
</body>
</html>
Using Form Submit Event
When the input is inside a form, ENTER naturally submits the form:
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page reload
const inputValue = this.querySelector('input').value;
alert('Form submitted with: ' + inputValue);
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Type and press Enter">
<p>Press Enter to submit the form.</p>
</form>
</body>
</html>
Comparison of Methods
| Method | Dependencies | Browser Support | Best For |
|---|---|---|---|
| jQuery keyup | jQuery required | All browsers | Legacy projects |
| Vanilla JS keydown | None | Modern browsers | New projects |
| Form submit | None | All browsers | Form inputs |
Key Points
- Use
event.key === 'Enter'instead ofkeyCode === 13for better readability - The
keydownevent fires before the character is inserted - The
keyupevent fires after the character is processed - Form submission is the most semantic approach for form inputs
Conclusion
Modern JavaScript with event.key === 'Enter' is the recommended approach. Use form submission events when dealing with forms, and avoid jQuery unless required by your project.
Advertisements
