Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

internet explorer - 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?

question from:https://stackoverflow.com/questions/7960773/jquery-remove-selected-attribute-of-option

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...