Reset fields to default values using jQuery

Have you ever wanted to reset only fields in a particular section of the form without resetting all of the fields?

Here is how you can achieve this with jQuery 🙂

$('#reset_address').click(function (event) {
 event.preventDefault();
 $('#address_details :input').each(function() {
  if ($(this).is('select')) {
   $(this).val($(this).find('option[selected]').val());
  } else {
   $(this).val(this.defaultValue);
  }
 });
});

#address_details represents a <fieldset> within my <form>. When the user clicks the #reset_address link I revert the fields within the <fieldset> (not the entire form) back to their original values.

Note: defaultValue is a core JavaScript property. A conditional check for <select> was necessary since defaultValue only applies to <input> and <textarea> fields.

Leave a Reply

Your email address will not be published. Required fields are marked *