reset

Reset form elements with jQuery

Posted on: November 8th, 2012 by taff No Comments

 

Reset form with jQuery is not as easy as I thought. I was using some jQuery love to send some form values via AJAX to a service when the submit button was clicked. I like to override submits with javascript, it slows down spam when used on contact forms and the like and is very fast to implement. The basic idea is on submit, hide the form and submit the data using the jQuery serialize() method. If the data is successfully submitted offer the user the option of resubmitting the form. If they click on the link, stop hiding the form and reset the fields so as to avoid confusion. I will add a post on how to submit a form with jQuery in the near future, but I am digressing, so back to the example. This was my first attempt and it failed miserably.

//Fails miserably
$("#create_teaser").reset();

After looking online there was quite a bit of talk about creating new jQuery methods and such, which seemed like a bit of an overkill to me.

Example of reset form with jQuery

This solution is about as simple as it gets when you want to reset form elements.

$("#create_teaser")[0].reset();

Reset form elements with Javascript

If you don't have jQuery available then you could just reset a form like this:

document.getElementById('myForm').reset();

which gets the element with the id myForm (in our case the form itself) and resets all the form elements to their original value.