How to change option value with Jquery?

允我心安 提交于 2019-12-10 15:23:00

问题


I am looking for a way to change the option value from a select tag when users click on a link.

For example I have a select option html:

<select> <option value="0">Please Select</option> 
<option value="1">red</option> 
<option value="2">white</option> 
</select>

And I have 2 links <a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a> When user clicks red the option will switch to red and white will switch to white. I am using the following code but it is not working.

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
        jQuery(this).parent('p').children("select :selected").text(title);
 });

Any suggestions?


回答1:


Your way will set the option's text to the title attribute. Try:

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
    jQuery(this).parent('p').find("select option").filter(function() {
        return $(this).text() == title;
    }).attr('selected', 'selected');
 });

See filter.




回答2:


Hmm, you're going about this wrong: Instead of changing the text of the selected option you need to loop over the <option/> elements and select the appropriate one, something like this:

$("select option").each(function() { 
    if($(this).text() == "red")) {
        this.selected = true; 
    }
});

Edit: There might be a select() function in jQuery. If that's the case then use that over the DOM property.




回答3:


This?

$("select #some-option").attr("selected", "selected");

Or this?

$("select").val(index);


来源:https://stackoverflow.com/questions/3269030/how-to-change-option-value-with-jquery

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