按值设置选择选项“已选择”

本文翻译自:Set select option 'selected', by value

I have a select field with some options in it. 我有一个select字段,其中包含一些选项。 Now I need to select one of those options with jQuery. 现在我需要使用jQuery选择其中一个options But how can I do that when I only know the value of the option that must be selected? 但是当我只知道必须选择的optionvalue时,我怎么能这样做呢?

I have the following HTML: 我有以下HTML:

<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

I need to select the option with value val2 . 我需要选择值为val2的选项。 How can this be done? 如何才能做到这一点?

Here's a demo page: http://jsfiddle.net/9Stxb/ 这是一个演示页面: http//jsfiddle.net/9Stxb/


#1楼

参考:https://stackoom.com/question/tzGo/按值设置选择选项-已选择


#2楼

要选择值为“val2”的选项:

$('.id_100 option[value=val2]').attr('selected','selected');

#3楼

Deselect all first and filter the selectable options: 首先取消选择全部并过滤可选选项:

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .attr('selected', true)

#4楼

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. 您可以使用属性选择器[attributename=optionalvalue]选择任何属性及其值,因此在您的情况下,您可以选择该选项并设置所选属性。

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

Where value is the value you wish to select by. 其中value是您希望选择的值。

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);

#5楼

There's an easier way that doesn't require you to go into the options tag: 有一种更简单的方法,不需要你进入options标签:

$("div.id_100 select").val("val2");

Check out the this jQuery method . 看看这个jQuery方法


#6楼

I think the easiest way is selecting to set val(), but you can check the following. 我认为最简单的方法是选择设置val(),但您可以检查以下内容。 See How to handle select and option tag in jQuery? 请参阅如何在jQuery中处理select和option标记? for more details about options. 有关选项的更多详细信息。

$('div.id_100  option[value="val2"]').prop("selected", true);

$('id_100').val('val2');

Not optimised, but the following logic is also useful in some cases. 未经优化,但以下逻辑在某些情况下也很有用。

$('.id_100 option').each(function() {
    if($(this).val() == 'val2') {
        $(this).prop("selected", true);
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值