当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Reset form values in JQuery Validator submitHandler

问题描述:

I Have a simple Jquery Validation that calls Ajax, but after call the Ajax page I want to reset the form. All works fine but its do not reseting the form.

My JQuery and Validate Script:

var validator = $('#formOne').validate({

rules: {

fieldName: {

required: true,

minlength: 3

}

},

submitHandler: function(form) {

$(this).callAjax(form);

validator.resetForm();

return false; //avoid form submit

}

});

//Ajax call function

$.fn.callAjax= function(form){

var postData = $(form).serialize();

var formAction = $(form).attr('action')

$.ajax({

type: "POST",

url: formAction,

data: postData,

dataType: "html",

success: function(response){

$("#ShowNames").html(response);

}

});

}

My Form:

<form name="formOne" id="formOne" method="post" action="ajax/insert_name.php?act=insert">

<input type="text" id="fieldName" name="fieldName">

<button type="submit" id="loading-btn" value="Submit" data-loading-text="Loading...">Avançar</button>

</form>

<div id="ShowNames"></div>

I've tried lots of ways but I couldn't make this work...

Any Ideas?

网友答案:

EDIT

Taking into account you're using the jQuery Validation plugin, a better and more concise answer has been provided by Dox.

I'm not sure why you used $validator.resetForm(); because I don't see $validator referencing anything. That being said, you should probably either clear your form in your AJAX success function, or check if some condition is true after your AJAX function runs.

The code you're looking for (if used in the AJAX success function) would look like:

//Ajax call function
$.fn.callAjax= function(form){
        var postData = $(form).serialize(); 
        var formAction = $(form).attr('action')     
        $.ajax({ 
            type: "POST",
            url: formAction,
            data: postData,          
            dataType: "html",      
            success: function(response){                    
                $("#ShowNames").html(response); 
                // If some condition is true
                $(form)[0].reset();
            }           
        });
 }
网友答案:
validator.resetForm();

Without $

Documentation

分享给朋友:
您可能感兴趣的文章:
随机阅读: