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

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

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?

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

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