1DMF
1DMF

Reputation: 2145

HTML5 'required' leaving invalid pseudo class when form reset

I have a form that uses HTML5 'required' validation, I have found if you try to submit the form in IE, the inputs are highlighted in red with the invalid pseudo class - fine.

If I then complete the form and submit it via AJAX, then issue a form.reset() upon success, the invalid pseudo class is re-applied to the form elements highlighting all the 'required' inputs in red?

How do I reset / clear the form totally including the invalid pseudo class?

Upvotes: 7

Views: 1058

Answers (2)

bharat
bharat

Reputation: 1776

You can store whole form tag to javascript variable then restore to parent element after submit or reset() time that will create new form & replace older form like..

//store after page load to reset when require-
var oldfrmcode=jQuery('.formcontainer').html();

//place following code to reset form require place
jQuery('.formcontainer').html(oldfrmcode);

Upvotes: 0

1DMF
1DMF

Reputation: 2145

I found this to be the ideal solution that appears to be working cross browser.

Simply add the novalidate attribute to the form, reset the form, then remove it - simples!

$('#my_form').attr('novalidate','novalidate');
$('#my_form').get(0).reset();    
$('#my_form').removeAttr('novalidate');

UPDATE : OK, Huston we have a problem....

It has fixed the issue in IE, but now it's causing a problem in Firefox!

Works fine in Chrome and Opera.

Why is FF running the validation checks when the novalidate attribute is removed from the form?

Not ideal but I guess I could always use...

if(/trident/i.test(navigator.userAgent))
{
    $('#my_form').attr('novalidate','novalidate');
    $('#my_form').get(0).reset();
    $('#my_form').removeAttr('novalidate'); 
}
else
{
    $('#my_form').get(0).reset(); 
}

Any other suggestions welcome.

Upvotes: 1

Related Questions