Reputation:
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());
}
});
};
Upvotes: 7
Views: 18056
Reputation: 22595
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.
$("#top1 select").each(function() {
this.defaultValue = $(this).val();
});
$(".reset").click(function() {
$('#top1 :input').each(function() {
$(this).val(this.defaultValue);
});
});
Upvotes: 2
Reputation: 36
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:
var defaultValue;
$(this).find('option').each(function (i, o) {
if (o.defaultSelected) {
defaultValue = o.value;
return;
}
});
Less elegant, but works in IE.
Upvotes: 2
Reputation: 42893
I used the following snippet to achieve this:
$(this).val($(this).find('option[selected]').val());
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).find('option').each(function(i, opt) {
opt.selected = opt.defaultSelected;
});
This does work for single selects, too.
Upvotes: 13
Reputation: 630349
Usually the default is the first <option>
in the <select>
, so you can do that:
$(this).find("option:first").attr("selected", true);
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:
if (tag == 'form')
this.reset();
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!
Upvotes: 3