1

I have an HTML select on the page. I have a timeout function where I set a value of this select element. My problem is that if a user opens this select before the timeout function runs, I cannot set a value in it.

In Chrome, the value of the select is set and dropdown in select is closed automatically. In Safari, the of the select is not set and dropdown never closes.

This is my HTML:

<select id="mySelect">
    <option value="-">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

This is my js:

setTimeout(function () {
    console.info('in timeout');
    var select = document.getElementById("mySelect");
    document.getElementsByTagName('body')[0].click();
    select.value = "3";
    select[3].click();
    console.info('in timeout end');
}, 7000);

This is a link on the codepen that reproduces this behaviour: https://codepen.io/annmirosh9/pen/WqNEEq

I tested it in Safari Version 12.0.3, and if I open a dropdown right after the page is loaded, dropdown will never be closed and value won't be set there.

Can you please tell me what I missed and how I can make this example works?

Anna Miroshnichenko
  • 1,143
  • 1
  • 7
  • 24

1 Answers1

1

This solution seems to work. Replace select[3].click(); with the following:

select.dispatchEvent(new Event("change", { bubbles: true }));

Based on the answer at https://stackoverflow.com/a/48775667.

Mike
  • 11
  • 1