jQuery

How to detect the Enter key in a text input field using jQuery

In this tutorial, we are going to see how to detect the Enter key in a text input field using jQuery. To check if a user has pressed the Enter key, you can use the “keypress” event in combination with the code 13 (Enter key). The following example displays the entered text in a dialog box when you press Enter on the keyboard.
 

How to detect the Enter key in a text input field using jQuery
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Detect the Enter key in a text input field</title>
		<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
		<script>
			$(document).on("keypress", "input", function(e){
				if(e.which == 13){
					var val = $(this).val();
					alert("You have typed: " + val);
				}
			});
		</script>
	</head>
	<body>
		<p><b>Type something and hit the enter key.</b></p>   
		<p><input type="text"></p>      
	</body>
</html>
Result

Type something and hit the enter key.

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *