Jquery validation not working after clearing a form
I have applied validation through JQuery Validation Plugin on my page. The validation works fine but once the Clear
button is hit to clear out all the fields on the form, and then the save button is clicked again, the validation doesn't fire and the form gets submitted. I have called the following javascript function on click of Clear
button to clear out all the form fields :-
function ResetForm() {
jQuery(':input', '#form1')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
return false;
}
The Clear
button is on a ChildPage and ResetForm
function 开发者_Go百科is on the MasterPage. Anybody have any guess why its getting submitted after clearing the fields ?
input is an element and not a attribute or a pseudo selectable, the main issue I see in your code is the :
within the :input
Try changing to jQuery('#form1 input')
to fetch the list of inputs
Also change the not()
command to select filter the inputs by type
.not('[type="button"], [type="submit"], [type="reset"], [type="hidden"]')
also as for :hidden
there's several factors you should know about this.
- They have a CSS display value of none.
- They are form elements with type="hidden".
- Their width and height are explicitly set to 0.
- An ancestor element is hidden, so the element is not shown on the page.
In light of your comment please try this tested version:
function resetForm()
{
$("#form1").find(':input').each(function()
{
var jelem = $(this);
switch(this.type)
{
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
jelem.val('');
break;
case 'checkbox':
case 'radio':
jelem.attr('checked',false);
}
});
}
@source: http://www.electrictoolbox.com/jquery-clear-form/
Another way to do this is to create a hidden input in your form but set the type as reset
like so:
<input type="reset" style="display:none" />
and then do:
function resetForm()
{
$("#form1[type='reset']").click();
}
Actually the error was something else, the code provided by RobertPitt
is correct for clearing of form fields and my code was also correct for clearing of form fields. But the problem is that, on the clear
button I had applied a class="cancel"
so that the form should not get submitted because it was an aspx:button
.
But according to what is written in JQuery docs, clicking of a button whose class is cancel
should skip the validation, but after that if I click on a normal submit
button validation should fire which was not firing in my case.
I just removed the cancel
class and it worked.
Does this help?
Reseting the form when usering the jquery validations plugin
精彩评论