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

JavaScript

路易Green

2020-03-10

我尝试用jQuery检查单选按钮。这是我的代码:

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

和JavaScript:

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

不起作用:

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

不起作用:

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

不起作用:

你还有其他主意吗?我想念什么?

第423篇《如何使用jQuery检查单选按钮?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
米亚伽罗L 2020.03.10

try this

 $("input:checked", "#radioButton").val()

if checked returns True if not checked returns False

jQuery v1.10.1
斯丁村村 2020.03.10

Try this

var isChecked = $("#radio_1")[0].checked;
Near小哥Green 2020.03.10

出乎意料的是,尽管有评论,但最流行和最受欢迎的答案忽略了触发适当的事件。确保调用 .change(),否则所有“更改时”绑定都将忽略此事件。

$("#radio_1").prop("checked", true).change();
猿路易 2020.03.10
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});
Davaid梅 2020.03.10

jQuery 1.6中添加的另一个功能prop()达到了相同的目的。

$("#radio_1").prop("checked", true); 
凯Harry 2020.03.10

简短易读的选项:

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

它返回true或false,因此您可以在“ if”语句中使用它。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android