简体   繁体   中英

How to set attribute of select option by targeting value instead of index

When a user clicks on a particular div (in my case a palette of swatches) I need that click to set the "selected" attribute of an option in a select list to "selected". This is working when I can target the option by its index with something like this:

onClick="getElementById('the_select')
         .options[2].setAttribute('selected', 'selected');"

But this doesn't work when I try to target the option by its value like this:

 onClick="getElementById('the_select')
         .option[value='blue'].setAttribute('selected', 'selected');"

I need to target the value because in this case "blue" is not always going to be in the same place in the select list.

How can I accomplish this?

我猜你可以做这样的事情:

document.getElementById("my_select").selected=true;

I found a workable solution using straight javascript based on a post by Dave on this thread...

jQuery - setting the selected value of a select control via its text description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM