Rotan075 Rotan075 - 3 months ago 5
HTML Question

The property selected is not been set within my select object

I want to change the value of my dropdown with jQuery. I use the following code:

<select id="id145" name="id145" class="dropdown" >
<option selected="selected" value="0">1 - test</option>
<option value="1">2 - test</option>
</select>


with the following JS:

$('[name=id145] option').filter(function() {
return ($(this).val() == '1');
}).prop('selected', true);


I see that within my dropdown the value 1 (2 - test) is selected but whenever I look at the source code, by using the inspector tools, I still see this:

<option selected="selected" value="0">1 - test</option>
<option value="1">2 - test</option>


What I expected to see, and does not happen, is this:

<option value="0">1 - test</option>
<option selected="selected" value="1">2 - test</option>


Does anyone know why? and is this even possible?

DEMO HERE

Answer

You've said that even using a DOM inspector (e.g., right-click the select and choose "Inspect element") you're still seeing selected="selected" on the first option, not the second. (And I can confirm that; I do too.)

The selected attribute sets the default state of the option; it doesn't necessarily reflect its current state. From the specification:

The selected attribute is a boolean attribute. It represents the default selectedness of the element.

(my emphasis)

The element's selected property tells you its current state, not the attribute. It's like the value attribute on input elements (which also sets the default value, not the current value). If that select box were in a form and you called reset on the form, the first option would be selected again, because that's the default for the select box.

If you want to know whether an option is currently selected, that information isn't available at the attribute level. You have to inspect the property instead:

$('[name=id145]').val('1');
$("[name=id145] option").each(function() {
  console.log("Option " + this.value + ": Selected? " + this.selected); // or $(this).prop("selected")
});
<select id="id145" name="id145" class="dropdown" >
    <option selected="selected" value="0">1 - test</option>
    <option value="1">2 - test</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>