Q:

How to detect if enter key is pressed in a text input field using jQuery

0

How to detect if enter key is pressed in a text input field using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the keypress event

To check whether a user has pressed Enter key while on specific input, you can use the keypress event in combination with the enter key code 13. The following example will display the inputted text in an alert box when you press the enter key on the keyboard.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Detect the Enter Key in a Text Input Field with jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).on("keypress", "input", function(e){
        if(e.which == 13){
            var inputVal = $(this).val();
            alert("You've entered: " + inputVal);
        }
    });
</script>
</head>
<body>
    <p><strong>Note:</strong> Type something in the text input box and press enter key.</p>      
    <p><input type="text"></p>      
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to change the background color of a web page d... >>
<< How to detect enter key press on keyboard using jQ...