Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery remove "selected" attribute of option?

Why doesn't this work in IE8 to deselect all options in a multiline selectbox?

$("#myselect").children().removeAttr("selected"); 

Is there a workaround? Nothing I could think of (attr("selected","") etc) seems to work.

UPDATE: Here is an updated jsFiddle. I have at least got it to degrade so that in IE8 the first option is selected. But without the hardcoded selected='selected' and the .attr call that IE8 seems to need, it does 3 different things in Firefox, Chrome and IE8! See this version:, which is simple and seems like it should work:

  • in Firefox: nothing selected
  • in Chrome: 0th option selected
  • in IE8: 1st option selected

Maybe I have made myself crazy and there is a mistake in there somewhere I can't see?

like image 569
Don Zacharias Avatar asked Oct 31 '11 22:10

Don Zacharias


People also ask

How do I remove a selected value from a Dropdownlist?

The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value='optionValue') on the select box. The remove() method is then used to remove this selected option. The find() method can be used to find the option in the value with the value selector.

How to remove an option from a dropdown in jQuery?

To remove an option from a dropdown list, you can use jQuery's . remove() method. The . remove() method will remove the specified elements out of the DOM.

How do you remove all options from select in jQuery except first?

Explanation: If we want to remove all items from dropdown except the first item then we can use $('#ddlItems option:not(:first)'). remove(); Here we have excluded first item from being deleted. If we want to remove all items from dropdown except the last item then we can use $('#ddlItems option:not(:last)').


2 Answers

The question is asked in a misleading manner. "Removing the selected attribute" and "deselecting all options" are entirely different things.

To deselect all options in a documented, cross-browser manner use either

$("select").val([]); 

or

// Note the use of .prop instead of .attr $("select option").prop("selected", false); 
like image 139
Jon Avatar answered Sep 24 '22 19:09

Jon


This works:

$("#myselect").find('option').removeAttr("selected"); 

or

$("#myselect").find('option:selected').removeAttr("selected"); 

jsFiddle

like image 33
Gabe Avatar answered Sep 20 '22 19:09

Gabe