How to simulate option selection? click() doesn't work

Advertisements

I want to simulate a user click on certain option, so I use click() on the <option> but it doesn’t work:

let select = document.getElementById("select");
select.addEventListener("change", changeSelection);

function changeSelection() {
  console.log("Clicked");
}

let option = select.querySelector(`option[value="3"]`);
option.click();
<select id="select">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

How can I do it?

>Solution :

The problem with option in a select is they are a "windowed" element and you really have issue working with them.

Typically if you want to select an option either you set the value of the select or if it is multiple select, set the selected attributes of the options. Since setting the value does not trigger change events, you would need to manually trigger it.

Single Select

let select = document.getElementById("select");
select.addEventListener("change", changeSelection);

function changeSelection() {
  console.log("Clicked", this.value);
}

select.value = 3;
select.dispatchEvent(new Event('change'));
<select id="select">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Multiple select

let select = document.getElementById("select");
select.addEventListener("change", changeSelection);

function changeSelection() {
  const values = Array.from(this.querySelectorAll("option:checked")).map(opt => opt.value);
  console.log("Clicked", values);
}


var opts = select.querySelectorAll("option");
opts[0].selected = true;
opts[2].selected = true;

select.dispatchEvent(new Event('change'));
<select id="select" multiple="multiple">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Leave a ReplyCancel reply