Related Articles

Related Articles

How to submit a form on Enter button using jQuery ?
  • Last Updated : 18 Aug, 2020

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.

filter_none

edit
close

play_arrow

link
brightness_4
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>
        <input name="lname" /><br>
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>

chevron_right


JavaScript Code:

filter_none

edit
close

play_arrow

link
brightness_4
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>

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
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>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :