Open In App

How to submit a form on Enter button using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

Given an HTML form and the task is to submit the form after clicking the ‘Enter’ button using jQuery. To submit the form using ‘Enter’ button, we will use jQuery keypress() method and to check the ‘Enter’ button is pressed or not, we will use ‘Enter’ button key code value.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
        crossorigin="anonymous">
    </script>
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h3 style="color: green;font-size: 28px;">
        GeeksforGeeks
    </h3>
  
    <form class="info">
        <input name="fname" /><br>
        <input name="lname" /><br>
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>


JavaScript Code:




<script>
  
    // Wait for document to load
    $(document).ready(() => {
        $('.info').on('submit', () => {
  
            // prevents default behaviour
            // Prevents event propagation
            return false;
        });
    });
    $('.info').keypress((e) => {
  
        // Enter key corresponds to number 13
        if (e.which === 13) {
            $('.info').submit();
            console.log('form submitted');
        }
    })
</script>


Explanation:
We use the jQuery event.which to check the keycode on the keypress. The keycode for the enter key is 13, so if the keycode matches to thirteen then we use the .submit() method on the form element to submit the form.

Complete Code:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
        integrity=
        "sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
        crossorigin="anonymous">
    </script>
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h3 style="color: green;font-size: 28px;">
        GeeksforGeeks
    </h3>
    <form class="info">
        <input name="fname" /><br><br>
        <input name="lname" /><br><br>
        <button type="submit">Submit</button>
    </form>
  
    <script>
        $(document).ready(() => {
            $('.info').on('submit', () => {
                return false;
            });
        });
        $('.info').keypress((e) => {
            if (e.which === 13) {
                $('.info').submit();
                alert('Form submitted successfully.')
            }
        })
    </script>
</body>
  
</html>


Output:



Last Updated : 18 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads