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:
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.
>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 = falseon everyHTMLOptionElementunless its owner<select>has<select multiple="multiple">(which you don’t), so just setoptions[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):


