问题
I'm using this "empty optgroup" workaround to get iOS to show option
elements with long text in a readable manner. I'm using the following code to test this solution:
<p>Choose something:</p>
<select>
<option>Option A</option>
<option>Some other option which is much longer than the first two options that has a distinguising feature at the end: B!</option>
<option>Some other option which is much longer than the first two options that has a distinguising feature at the end: C!</option>
<option>Option D</option>
<option>Option E</option>
<option>Option F</option>
<option>Option G</option>
<optgroup label=""></optgroup>
</select>
optgroup { display: none; }
It does make iOS Safari display the long options wrapped so they're distinguishable again, but it opens up another problem where multiple items seem selected even though it is a single select dropdown.
To reproduce:
- Open this jsFiddle's fullscreen result on a fully updated iPhone 4S;
- Tap the
select
to open it.
Notice that "Option A" is now selected.
- Scroll down in the native dropdown control until "Option A" is no longer visible.
- Tap to select "Option E".
- Scroll a bit back.
End result is that two options seem to be selected:
The expected result obviously is that only "E" is selected.
How can I solve this issue?
回答1:
I found this issue without the optgroup
element, when I was programmatically re-populating and selecting a default item in a combo box, in response to another field changing. I found that I simply had to clear out the old selection first:
$("#time")[0].selectedIndex = -1 // this fixed it for me
$("#time option").each(function () {
if ($(this).val() == oldtime) {
$(this).attr("selected", "selected");
return;
}
});
Only Safari had this problem, it's clearly a bug that a single-select list can have two items visibly selected.
来源:https://stackoverflow.com/questions/31913173/ios-safari-selecting-multiple-options-visually-for-single-select