Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> attributes are set. Curious.

enter image description here

>Solution :

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.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:

iPad OS 15.1 (yeah, I’m still not on 15.6):

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading