EnexoOnoma
EnexoOnoma

Reputation: 8836

Dropdown auto select on data attribute

I use this code to autoselect an option on a dropdown. How can I change it so as to not match the value, but tha data-id attribute?

   window.onload = function(){
       document.getElementsByName("program")[0].value=+param1;
   }
<select name="program">
    <option data-id="1234" value="567">text</option>
<option data-id="897" value="65475">text</option>
</select>

Upvotes: 0

Views: 451

Answers (1)

trincot
trincot

Reputation: 350137

You can do that by looking for that attribute value with querySelector() and setting the found option's selected attribute.

I would also suggest to respond to the document.DOMContentLoaded event instead of window.load:

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('option[data-id="1234"]')
            .setAttribute('selected', 'selected');
});
<select>
    <option data-id="12" value="7">other option</option>
    <option data-id="1234" value="567">select this</option>
</select>

Upvotes: 1

Related Questions