views:

194

answers:

2

Javascript has textObject.defaultValue=somevalue for retrieving the default value (stored value from page load) of an input even if you wipe the input and replace the contents, you can still get the default back. Like this:

// in the html page
<input id="addr1" type="text" value="21 Oak St." />

// the jquery
myInput = $("#addr1"); // the input, default value on page load = 21 Oak St.

$(myInput).val('51 New St'); // wipe default and set new

// alerts 21 Oak St
alert($(myInput).val($(myInput)[0].defaultValue));

How do you accomplish this on a select?

selectedIndex is boolean, not the value, so that does not work.

Thanks!

+4  A: 

You probably want to look at the "defaultSelected" attribute of "option" elements.

Initially, "defaultSelected" will be true if the original HTML of the option tag had an explicit "selected" attribute. You can change that by setting the attribute on option tags with Javascript after the page has loaded, in response to whatever conditions you like.

Pointy
+1 Didn't know about this one, nice.
bendewey
A: 

there may be multiple "selected" option elements, in that case pick the first if no other requirements are set. @Pointy tip is correct but be aware that the "defaultValue" property can be overwritten by other code in the same page. If it were read-only it would be more useful :-)

Diego Perini