Reputation: 124
I'm trying to remember the selected item of a select or multi-select form element in a contenteditable
block. For Firefox and Chrome, I can just remember the selected item(s), remove the selected
attributes and tag the ones that should have it. Normal DOM serialization will take care of the rest.
Trying to do this with IE or Edge fails miserable, since it just doesn't work. The following is a small test case:
<!DOCTYPE html>
<html>
<body>
<select multiple>
<option id="op1" selected value="1">1</option>
</select>
<button onclick="var op1 = getElementById('op1'); op1.removeAttribute('selected'); alert(op1.outerHTML);">Test </button>
</body>
</html>
Does anyone have a method that works without having to clone the options that have the attribute and replacing the current nodes with them? Target would be IE 8+ and Edge; older IE is not of interest.
Upvotes: 4
Views: 1747
Reputation: 124
Based on the suggestion from user3297291, a follow-up search found Issue #12087679 for Edge. Integrating the suggestions from that gives the following, which works in all of IE11, Edge, Chrome and Firefox:
<!DOCTYPE html>
<html>
<body>
<select multiple>
<option id="op1" selected value="1">1</option>
</select>
<button onclick="var op1 = getElementById('op1');
op1.setAttribute('selected', false);
op1.selected = false;
op1.removeAttribute('selected');
alert(op1.outerHTML);">Test </button>
</body>
</html>
First, explicitly ensure that the attribute is a boolean value, the default is not (Edge bug). Next, disable the property to make Microsoft browsers also remove the attribute. Finally, remove the attribute for the rest of the world that implements DOM level 1.
Upvotes: 2