1

I have some jQuery code that selects an option in a select list. The first time it selects an item everything works, however the second pass through IE and FF do not clear the selected items. Chrome always works.

I have created a JSFiddle with a demo of what I am seeing. I have tried both $("testUpdate option:selected") and $("testUpdate > option:selected") as selectors, each work the first time only. I have tried changing the multiple tag to just multiple per this documentation.

Here is the HTML and relevant failing jQuery. I have been using jQuery 1.9.1, but on JSFiddle I see the same results with newer versions.

//HTML
<select id="testUpdate" name="testUpdateName" multiple="multiple" size="5">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

//jQuery that fails the 2nd pass
$("#testUpdate option:selected").each(function () {
    //This is not executed
    $(this).removeAttr('selected');
});

//Alternate selector to force all options to always be checked
//HTML is correct after this, but visually the list is not selected
//I would also prefer not to do this because the actual list will be hundreds of items
$("#testUpdate option").each(function () {
   $(this).removeAttr('selected');
});
JabberwockyDecompiler
  • 3,318
  • 2
  • 42
  • 54

1 Answers1

1

The selected value does not get added to the DOM element, and is therefore not an attribute of the option. You should use $.prop():

$("#testUpdate option[value='" + this.getCurrentSelectionValue() + "']").prop('selected', 'selected');

Fiddle

Bic
  • 3,141
  • 18
  • 29
  • 1
    `$.prop()` won't update the actual DOM; it will just change the appearance of the element. If you look at the HTML rendering in any of the debuggers, you won't see that `selected` property on the options. If you want the DOM updated as well, then you'll need to use both `$.attr()` and `$.prop()`. – Bic Feb 18 '14 at 16:47
  • Ahh, I see now with this question the difference. [prop vs attr](http://stackoverflow.com/questions/5874652/prop-vs-attr) – JabberwockyDecompiler Feb 18 '14 at 16:48