Set selected using jQuery

徘徊边缘 提交于 2019-12-08 06:22:22

问题


I'm trying to change the selected option within this list.. Its only working for some and not others?

selectedVal will either be Kelly Green, Navy etc...

 var selectedVal = $(this).text();

 $("#product-variants-option-0 option[text=" + selectedVal+"]").attr("selected","selected") ;

This is the select list:

<select class="single-option-selector" id="product-variants-option-0">
<option value="Gunmetal Heather">Gunmetal Heather</option>
<option value="Kelly Green">Kelly Green</option>
<option value="Navy">Navy</option>
</select>

回答1:


Use value attribute instead of text in your selector. i.e:

$("#product-variants-option-0 option[value=" + selectedVal+"]").attr("selected","selected") ;



回答2:


There's a much simpler way to set the selected option of a <select> element.

Just call jQuery's .val() method against the <select> itself:

$("#product-variants-option-0").val( selectedVal );


来源:https://stackoverflow.com/questions/4572567/set-selected-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!