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?
>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).