如何使用jQuery检查单选按钮?

本文翻译自:How to check a radio button with jQuery?

I try to check a radio button with jQuery. 我尝试用jQuery检查一个单选按钮。 Here's my code: 这是我的代码:

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

And the JavaScript: 和JavaScript:

jQuery("#radio_1").attr('checked', true);

Doesn't work: 不起作用:

jQuery("input[value='1']").attr('checked', true);

Doesn't work: 不起作用:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work: 不起作用:

Do you have another idea? 你有其他想法吗? What am I missing? 我错过了什么?


#1楼

参考:https://stackoom.com/question/Nlxj/如何使用jQuery检查单选按钮


#2楼

Short and easy to read option: 简短易读的选项:

$("#radio_1").is(":checked")

It returns true or false, so you can use it in "if" statement. 它返回true或false,因此您可以在“if”语句中使用它。


#3楼

Try this. 试试这个。

In this example, I'm targeting it with its input name and value 在这个例子中,我用它的输入名称和值来定位它

$("input[name=background][value='some value']").prop("checked",true);

Good to know: in case of multi-word value, it will work because of apostrophes, too. 很高兴知道:在多字值的情况下,它也会因为撇号而起作用。


#4楼

Try this. 试试这个。

To check Radio button using Value use this. 要使用Value检查单选按钮,请使用此选项。

$('input[name=type][value=2]').attr('checked', true); 

Or 要么

$('input[name=type][value=2]').attr('checked', 'checked');

Or 要么

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this. 要使用ID检查单选按钮,请使用此选项。

$('#radio_1').attr('checked','checked');

Or 要么

$('#radio_1').prop('checked','checked');

#5楼

试试这个

var isChecked = $("#radio_1")[0].checked;

#6楼

The $.prop way is better: $.prop方式更好:

$(document).ready(function () {                            
    $("#radio_1").prop('checked', true);        
});

and you can test it like the following: 你可以像下面这样测试它:

$(document).ready(function () {                            
    $("#radio_1, #radio_2", "#radio_3").change(function () {
        if ($("#radio_1").is(":checked")) {
            $('#div1').show();
        }
        else if ($("#radio_2").is(":checked")) {
            $('#div2').show();
        }
        else 
            $('#div3').show();
    });        
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值