jquery validation submit - with ajax submit - click function

♀尐吖头ヾ 提交于 2019-12-25 05:06:29

问题


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:


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.



来源:https://stackoverflow.com/questions/11462587/jquery-validation-submit-with-ajax-submit-click-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!