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

I need to set a select to selected using data-val

I have a select I need to set to selected but the select is using a name and the options are using "data-val" and I can’t change either:

<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 2</option>
</select>

How can I set Option 2 to selected using JavaScript?

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 :

A couple ways that you could go about this;

You could be very explicit and set the value of the <select /> itself through;

document.querySelector('[name="properties[Liner]"]').value = "Option 2";

Or you could be a little bit more dynamic with the following;

document.querySelector('[name="properties[Liner]"]').value = document.querySelector('[data-val="2"]').value;
  • For the targeting of the name, you’ll want to use [name="{some name}"]
  • For the targeting of a data-attribute, you’ll want to use [data-val="{some value}"]

In this scenario, you could just specify "name" for querySelector and you’ll get what you want because there’s only one element with a name on the page (at least in your mini-scenario).

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