SOLVED: JavaScript error .reset is not a function

Read this article if you are trying to call reset() on a <form> DOM element but you're getting an error stating .reset is not a function.

PROBLEM

I was working on some jquery UI code and I wanted to reset the form when the dialog was closed. I found a simple snippet explaining how to do this:

$(this).find("form")[0].reset();

If you aren’t familiar with this notation the [0] gets the underlying DOM object rather than the jQuery object – reset() is a built in JavaScript feature.

Other developers seemed happy with this function, reporting that it solved their problem but in my testing all I was seeing was Firefox's error console filling up with “.reset is not a function” errors.

After wrestling with this problem for a few minutes I tracked this down to a simple solution.

SOLUTION

If you are seeing this error in your code then it’s more than likely due to the fact that you have an element in your form with an id of “reset”.  If you do then the .reset() is masked by this element.

For me the offending code was this:

<input name="reset" type="reset" id="reset" value="Reset" />

A simple change of the ID fixed my problem and I was on my way:

<input name="resetform" type="reset" id="resetform" value="Reset" />

And then I successfully used the following close handler in my jquery ui dialog:

var dialogSettings = {
  close: function(event, ui) {
    $(this).find('form').get(0).reset();
  }                       
};

You might not be in the same situation as me though. If you want to simple grab the form then just do a normal jQuery search for the id of the form. So to reset the following form:

<form id="more_information">

You would use the either of the following code snippets, depending on personal taste:

$("#more_information").get(0).reset();
$("#more_information")[0].reset();

kick it Shout it

7 comments :

Anonymous said...

You give me a big hand! Thanks!

Anonymous said...

A very simple solution to reset the document form is to just use the simple javascript methods of

document.forms[0].reset()

basic99 said...

yes. that really sucks that if you choose the wrong id it breaks something.

Anonymous said...

When i read following lines, i was so thankful to you man

"it’s more than likely due to the fact that you have an element in your form with an id of “reset”."

I was also this issue for long time.

Once again big thanks :)

Anonymous said...

Thanks a lot, It worked. Save to lot of head starching time

Anonymous said...

Thank you for the explanation! Makes total sense now.

Neethu said...

Or you can use

$('#formId')[0].reset.click();