jquery validation submit - with ajax submit - clic

2019-09-13 13:10发布

I'm using a click function on a link to submit the form via ajax, and if the server returns with an error, a server side error is displayed.

With this method, the enter key doesn't work in the form, and I think there's probably an easier and more correct way to do this with jquery validation's submit handler.

here's my code so far...

function loginSubmit(){
    $.ajax({
        url: loginFormURL,          
        type: 'POST',
        /** contentType: "application/json;",  **/
        dataType:"text json",
        /** async: true, **/
        data:$('#loginForm').serialize(),
        success: function(data){

           if(data.isError == "false" || data.isError == ""){

                       $.postMessage(
                        'redirectURL|'+ redirectURL +'',
                        '*',
                        parent
                      );


                     } else

                     if(data.isError == "true"){

                       $("#loginError").empty().show(); 
                       // iterate over the message list and display the error
                       for (var i=0; i < data.errorMessages.length; i++){
                               // inject error message to the error container

                           $("#loginError").append(data.errorMessages[i]);

                           }    

                       // iterate over the field list and paint the fields in red

                       $('input').parent('div').addClass('inputError');



                   }

           }            
   });
} 

and the click function:

 $("a#loginButton").click(function(){
                $("#loginForm").validate().form(this);
                if($('#loginForm').valid()){
                    loginSubmit();
                }
            });

Any help would be appreciated.

1条回答
虎瘦雄心在
2楼-- · 2019-09-13 13:51

You'll want to listen for the ENTER keypress on your input fields:

$('input').keypress(function(event) {
    if(event.which == 13) {
        loginSubmit();
        event.preventDefault();
        return false;
    }
});

Of course you might not want to capture ENTER on all your INPUT tags, just some, so you could use another selector depending on your needs.

See a similar discussion here.

查看更多
登录 后发表回答