I have a dropdown that has many time zones as options:
<select data-drupal-selector="edit-field-user-timezone" id="edit-field-user-timezone" name="field_user_timezone">
<option value="_none" selected="selected"></option>
<optgroup label="Africa">
<option value="Africa/Asmara">Asmara</option>
<option value="Africa/Bamako">Bamako</option>
<option value="Africa/Bangui">Bangui</option>
<option value="Africa/Banjul">Banjul</option>
I am trying to autoselect a value based on the client's time zone via JavaScript:
<script>document.getElementById("edit-field-user-timezone").selectedIndex = Intl.DateTimeFormat().resolvedOptions().timeZone</script>
But this is not doing anything. What am I doing wrong?
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) does indeed output my correct timezone in the same format of the dropdown.
Thanks
Try this:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const option = Object.values(document.getElementById("edit-field-user-timezone").options)
option.map(element => {
element.value == timezone ? element.selected = true : false
});
<select data-drupal-selector="edit-field-user-timezone" id="edit-field-user-timezone" name="field_user_timezone">
<option value="_none" selected="selected"></option>
<optgroup label="Africa">
<option value="Africa/Asmara">Asmara</option>
<option value="Africa/Bamako">Bamako</option>
<option value="Africa/Bangui">Bangui</option>
<option value="Africa/Banjul">Banjul</option>
</optgroup>
</select>
selectedIndex gives you the numerical index of the current selected option. It's a read-only property. To automatically select an option, you'd have to add the selected attribute to it. In this case, you'd have to find the option (or the index of the option) with the value matching the timezone, then toggle the selected attribute of that option.
Like this:
const options = [...document.getElementById('my-select').children]
const targetedValue = 'b' // equivalent to time zone in your case
const desiredOption = options.find(option => option.value === targetedValue)
desiredOption.selected = true
<select id="my-select">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>