locked
enter key to submit a form only RRS feed

  • Question

  • User-944424728 posted

    Hello, how do I add functionality to allow users to use the enter key to submit a form only when the focus is on a textbox form field. How to modify this to submit the form. Add code for each form input type except dropdown, combo box, or any type that requires opening. Thanks.

    $('input[type="text"]').keydown(function (event) {
    var KeyID = (window.event) ? event.keyCode : event.which;
    if (KeyID == 13) {
    event.preventDefault();
    return false;
    }
    });

    Wednesday, October 23, 2019 6:13 PM

Answers

  • User288213138 posted

    Hi aspvbnet,

    how do I add functionality to allow users to use the enter key to submit a form only when the focus is on a textbox form field.

    It depends on whether you are submitting the form wia submit() method or via an AJAX call.

    If you use submit() method, you can try below code.

    <script>
            $(document).ready(function () {
                $('input[type="text"]').keydown(function (event) {
                    var KeyID = (window.event) ? event.keyCode : event.which;
                    if (KeyID == 13) {
                        $('#form').submit();
                        event.preventDefault();
                        //return false;
                    }
                });
            });
        </script>

    More information about submit() you can refer to this link: https://api.jquery.com/submit/

    If you use ajax to submit a form, you can refer below code:

    <script>
            $(document).ready(function () {
                $('input[type="text"]').keydown(function (event) {
                    var KeyID = (window.event) ? event.keyCode : event.which;
                    if (KeyID == 13) {
                        $.ajax({
                            url: 'some-url',
                            type: 'post',
                            dataType: 'json',
                            data: $('#form').serialize(),
                            success: function (data) {
                                // ... do something with the data...
                            }
                        });
                    }
                });
            });
        </script>

    Best regards,

    Sam
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 3:05 AM