如何使用jQuery设置无线电选项onload

本文翻译自:how to set radio option checked onload with jQuery

How to set radio option checked onload with jQuery? 如何使用jQuery设置无线电选项onload?

Need to check if no default is set and then set a default 需要检查是否未设置默认值,然后设置默认值


#1楼

参考:https://stackoom.com/question/3EBp/如何使用jQuery设置无线电选项onload


#2楼

I liked the answer by @Amc. 我喜欢@Amc的答案。 I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). 我发现表达式可以进一步浓缩,不使用filter()调用(@chaiko显然也注意到了这一点)。 Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject. 另外,prop()是jQuery v1.6 +与attr()相关的方法,请参阅prop()jQuery文档,了解该主题的官方最佳实践。

Consider the same input tags from @Paolo Bergantino's answer. 考虑来自@Paolo Bergantino答案的相同输入标签。

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

The updated one-liner might read something like: 更新的单行可能会读取如下内容:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

#3楼

If you want it to be truly dynamic and select the radio that corresponds to the incoming data, this works. 如果您希望它是真正动态的并选择与传入数据相对应的无线电,则可以使用。 It's using the gender value of the data passed in or uses default. 它使用传入的数据的性别值或使用默认值。

if(data['gender'] == ''){
 $('input:radio[name="gender"][value="Male"]').prop('checked', true);
}else{
  $('input:radio[name="gender"][value="' + data['gender'] +'"]').prop('checked', true);
};

#4楼

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

#5楼

I think you can assume, that name is unique and all radio in group has the same name. 我想您可以假设,该名称是唯一的,并且组中的所有无线电都具有相同的名称。 Then you can use jQuery support like that: 然后你可以像这样使用jQuery支持:

$("[name=gender]").val(["Male"]);

Note: Passing array is important. 注意:传递数组很重要。

Conditioned version: 条件版本:

if (!$("[name=gender]:checked").length) {
    $("[name=gender]").val(["Male"]);
}

#6楼

//If you are doing it on javascript or a framework like backbone, you will encounter this a lot you could have something like this //如果你是在javascript或像骨干这样的框架上做的,你会遇到很多这样的东西

$MobileRadio = $( '#mobileUrlRadio' );

while

$MobileRadio.checked = true;

will not work, 不管用,

$MobileRadio[0].checked = true;

will. 将。

your selector can be as the other guys above recommended too. 您的选择器也可以像上面推荐的其他人一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值