I found code online to clear a form but it had nothing for a select box. With jquery i tried adding code to select the default option in the select box when i reset the form. I figured the only way to find the default was to look for where the SELECTED option was. I then discovered when the user selects something else jquery does not see selected as the default but as to the new option the user selected.
How do i get find the default option in the form so i can clear this properly?
//http://www.learningjquery.com/2007/08/clearing-form-data
$.fn.clearForm = function () {
return this.each(function () {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select') {
//alert($('option', this).size());
alert($('option[selected]', this).val());
}
});
};
Usually the default is the first
<option>
in the<select>
, so you can do that:Though, if you're resetting an entire form, you can reset it to what it was on page load with a
.reset()
call, like this:I'm not sure that's what you're really after, but just throwing it out there. Often the native DOM methods already there are very handy, don't ignore them!
I used the following snippet to achieve this:
option[selected]
will get the "hardcoded" selected option(s) (the default).option:selected
in contrast, will get the currently selected option(s).This will work for single selects, multi selects require a different approach:
This does work for single selects, too.
Koraktor's answer didn't work for me in Chrome either, and I couldn't use form.reset() because I wanted to reset a subset of the form. I found that the easiest thing to do was to give the selects a defaultValue when the page is loaded, then the reset function works using the same line on all elements returned by the :input selector.
I found that Koraktor's answer did not work in IE8 and lower. I solved it by iterating the options until finding the default selected one:
Less elegant, but works in IE.