Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"defaultValue" property for <select>?

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!

like image 596
PHP Systems Avatar asked Feb 27 '10 16:02

PHP Systems


2 Answers

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.

like image 117
Pointy Avatar answered Oct 18 '22 20:10

Pointy


This is the jquery that works for me:

$('select[name="name_of_select"] option[selected]').val()
like image 36
Davious Avatar answered Oct 18 '22 19:10

Davious