I use the code below to set default values for input objects. This works fine for text inputs but select dropdowns, radio buttons and check boxes are not reset to their default values.
How can I solve this?
function ResetForm(form) {
$(":input", form).not(":button, :submit, :reset, :hidden").each(function () {
this.value = this.defaultValue;
});
}
p.s. I use this method to reset inputs which are in a div node; I pass the div‘s id into this function.
defaultValueexists for radio buttons and checkboxes, but you have misunderstood what the “value” of these elements is. It is not “which” or “whether” is selected/checked, but the underlying value that is part of the form contents if the element is selected/checked… whereas you want the former.And
defaultValuesimply doesn’t exist forselect, which doesn’t really have a value, but one or more selectedoptionchildren.You have a couple of options here.
Option 1: Wrap the inputs in a form
You said you don’t have a form, but why not make it so that you do? Although the W3C spec doesn’t require that inputs be under a
<form />node, it would make sense.Then:
Or, if your
formis a jQuery element set (and it looks like it probably is):Option 2: Hack it
If you really insist, you can hack it about, caching initial values using a mix of
$.attrand$.prop. Make sure that you’re using jQuery 1.6.1+ though.Live demo.
(Note to other contributors: I originally looked at simply resetting the element to the state specified by
$.attr, but I guess even 1.6.1+’s$.attrdoesn’t work quite how I thought.)