Bill
Bill

Reputation: 1477

Clear form using jQuery

I'm using the code below to reset all of my values on a particular form.

        $('#' + frm).closest('form').find("input[type=text], textarea").val("");
        $('#' + frm).closest('form').find("input[type=password]").val("");
        $('#' + frm).find('input[type=checkbox]:checked').removeAttr('checked');
        $('#' + frm + ' input[type="radio"]').prop('checked', false);

It works fine for 95% of the cases but I would like to reset all of the Select box back to the selected index of 0. If there is a better or more efficient to do this entire process to reset all element types I'm open to the best suggestion. I need to reset the form because the same form will be used over and over again by the same person to add employment history.

Thanks for the input

Upvotes: 0

Views: 522

Answers (2)

Vladu Ionut
Vladu Ionut

Reputation: 8193

You could use Form reset() Method

The reset() method resets the values of all elements in a form (same as clicking the Reset button).

 $('#' + frm).closest('form')[0].reset();

Upvotes: 1

Bud Damyanov
Bud Damyanov

Reputation: 31899

You can implement your own reset form method:

jQuery.fn.reset = function(fn) {
   return fn ? this.bind("reset", fn) : this.trigger("reset");
 };

This would allow you to attach a code to a reset function:

jQuery("#form").reset(function(){ 
   /* some other code */ 
 });

You can (and still this is recommended way to do the things) use a simple HTML input of type reset - it will do the same even on browsers who have JavaScript disabled.

Upvotes: 1

Related Questions