dafodil
dafodil

Reputation: 513

Form submit on enter key press in jquery

i need to submit form on Enter Key press. I have tried below code, but nothing is happening.

My code is below

<script>
     $(function() {
$("#verifyForm").keypress(function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('button[type=submit]').click();
        validateSearch();
        return false;
    } else {
        return true;
    }
});

});

    <form:form modelAttribute="verifyFormModel" method="POST" name="verifyForm" action="verifyForm" id="verifyForm" onsubmit="return(validateSearch());" >
                <fieldset>
                    <ul>
                        <c:if test="${aVerifyFormModel.errorFlag == 1}">
                            <div id="messageText">The code you entered is invalid. Please check and re-enter.</div>
                        </c:if>
                        <div id="formError" style="display: none;"></div>
                        <li><label for="headerTxt">Code: <span class="req">*</span></label> 
                            <input id="formCode" size="50" maxlength="6" type="text" name="formCode" />
                        </li>
                    </ul>
                    <div >
                        <Button id="Display" name="Display" >Submit</Button>
                    </div>
                </fieldset>
            </form:form> 

What is wrong in my code? Any help is appreciated

Upvotes: 1

Views: 4456

Answers (4)

dafodil
dafodil

Reputation: 513

Thank you guys for all of your time, this below piece of code worked for me.

Add this code inside script

$(function() {
        $('#verifyForm').keypress(function(e) { //use form id
            if (e.which == 13) {
                validateSearch(); //-- to validate form 
                $('#verifyForm').submit();  // use form id
                return false;
            }
        });
    });

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Get the form by id:

document.getElementById("verifyForm").submit();

or go full jquery

$('body').on('keypress',function(e){
 var key = (e.keyCode || e.which);
    if(key == 13 || key == 3){
       $('#verifyForm').submit();
    }
});

Upvotes: 2

Ruhul
Ruhul

Reputation: 1030

Can you please try this??

$('#formCode').keypress(function (e) {
  if (e.which == 13) {
    $('#verifyForm').submit();
    return false;    
  }
});

Upvotes: 0

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

try this if using jquery:

if(key == 13 || key == 3){
  $('#verifyForm').submit()
}

Upvotes: 1

Related Questions