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?
CodePudding user response:
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).
CodePudding user response:
Code explanation in comments
(function(){
const selectEle = document.querySelector('[name="properties[Liner]"]'); // query the select the element
const setSelected = 2; // set the default value
const options = selectEle.querySelectorAll('option'); // query all the option element
options.forEach((option)=>{
const value = option.getAttribute('data-val'); // get the attribute data-val
if(value == setSelected){ // if matches
option.setAttribute('selected', true); // set selected
}
});
})();
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 3</option>
</select>