1

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?

3 Answers 3

5

<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/

Sign up to request clarification or add additional context in comments.

2 Comments

heavy stuff. this is the adequate one: w3schools.com/jsref/prop_option_defaultselected.asp ;)
@Commando: It looks pretty light to me ;-) Also, I avoid linking to w3schools wherever possible. Take that particular page, for example and I quote, "Note: If an option is selected by default, it is displayed first in the dropdown list." - That's just not right. Although MSDN doesn't always get it right either, at least the link I gave you in my answer also has a link to the W3C spec.
2

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.

5 Comments

and if a Commando, like myself, change the initial selected value with some other option from the list, how can I fetch & select the first one ever selected, durring the page load instantiation of the objects and elementsŠ?
Is this a CSS pseudo-class or a jQuery specific item? Trying to track down a link to option:selected and failing
@Jared This is a jQuery specific selector.
@Jared No problem! jQuery has several of it's own selectors that make things a lot easier (:input for example).
There's no need to re-invent the wheel with data here - as my answer explains, finding the default values is easy enough without it.
0
$('select option:selected').val();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.