iOS Safari shows blank <option> text despite setting HTMLOptionElement.label (but it works in Chrome), why?

Viewed 41

I'm having difficulties updating the value of an options (dropdown) HTML element.

What I'm trying to do is iterate over serveral dropdown values which are in an array, and update de value and label:

var options = document.getElementsByTagName('option');
var answers = [1,2,3]

for (var i = 0; i < answers.length; i++) {
    options[i + 1].value = answers[i];
    options[i + 1].label = answers[i];
    options[i + 1].selected = false;
 }
<div>
<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>
</div>

But after the code has run thedropdown looks like this:

enter image description here

Anyone know how to fix this? The shown code is actually working on other browsers.

———-

The Safari DOM inspector shows the <option>'s label="" and value="" attributes are correctly set. Curious...

enter image description here

1 Answers

The problem is that (as of September 2022) all versions of Safari prior to 15.6 do not display the text of the HTMLOptionElement.label property on-screen. (this affects both macOS Safari and iOS Safari, and Safari 15.6 was only released a few weeks ago).

  • Instead, just change .label = answers[i] to .textContent = answers[i], as below.
  • Also, you don't need to set .selected = false on every HTMLOptionElement unless its owner <select> has <select multiple="multiple"> (which you don't), so just set options[i].closest('select').selectedIndex = 0; to reset selection to the first <option>.

var options = document.getElementsByTagName('option');
var answers = [1,2,3]

for (var i = 0; i < answers.length; i++) {
    const a = answers[i].toString();
    const o = options[i+1];

    o.value       = a;
    o.label       = a; // <-- Safari (prior to v15.6) ignores .label and uses .textContent instead, so set both properties.
    o.textContent = a;

    const select = o.closest('select');
    if( select && select.selectedIndex !== 0 ) select.selectedIndex = 0;
}
<div>
<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>
</div>

Screenshot proof (after applying fix):

Chrome 105 on Windows iPad Safari 15.1
enter image description here enter image description here
Related