Set select option 'selected', by value

后端 未结 28 2939
攒了一身酷
攒了一身酷 2020-11-22 10:40

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the

28条回答
  •  醉话见心
    2020-11-22 11:23

    You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue], so in your case you can select the option and set the selected attribute.

    $("div.id_100 > select > option[value=" + value + "]").prop("selected",true);
    

    Where value is the value you wish to select by.

    If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute

    $("div.id_100 option:selected").prop("selected",false);
    $("div.id_100 option[value=" + value + "]")
            .prop("selected",true);
    

提交回复
热议问题