Reputation:
I'm using a third-party jQuery plugin that gets the values, settings and preferences of a <select>
element and replaces it with a custom widget.
How can I find out the default value of a <select>
element?
Upvotes: 1
Views: 6212
Reputation: 344565
<option>
elements have a property defined in DOM level 1 called defaultSelected
. This property will be set to true for any <option>
element that has the selected
attribute defined in the HTML when the element is parsed.
It should be fairly simple to use filter
to get any default selected options:
var def = $("select > option").filter(function () {
return this.defaultSelected;
});
Working demo: http://jsfiddle.net/AndyE/9G3pR/
Upvotes: 5
Reputation: 101483
Use
$("select option:selected");
To get the currently (or default) selected item. To get it's value, use
$("select option:selected").val();
Or
$("select").val()
If you want to be shorter/faster.
To get the select's original value, you need to store it in the element's data using the .data()
function, as this JSFiddle shows.
When you want to retrieve the value, simply call .data("originalValue")
on the select element (second .each()
of the JSFiddle.
$(document).ready(function() {
$("select").each(function() {
$(this).data("originalValue", $(this).val());
});
// Log data - will output "1"
$("select").each(function() {
console.log($(this).data("originalValue"));
});
});
You need to run the first .each()
call in the above code when your page loads to store the select box's original value. Do note that originalValue
can be any identifier you like.
Upvotes: 2