我尝试用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);

不工作:

你还有别的主意吗?我错过了什么?


当前回答

$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});

其他回答

$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

这个答案要感谢Paul LeBeau的评论。我想我应该把它写下来作为一个正确的答案,因为令人惊讶的是没有答案。

唯一对我有用的(jQuery 1.12.4, Chrome 86)是:

$(".js-my-radio-button").trigger("click");

这可以完成我想要的一切—更改选定的单选按钮(无论是视觉上还是编程上)并触发事件,例如更改单选按钮。

只是像其他答案建议的那样设置“checked”属性不会改变我选择的单选按钮。

你必须做

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

这就是HTML属性

如果你不想为这么简单的事情包含一个像jQuery这样的大库,这里有一个使用内置DOM方法的替代解决方案:

// Check checkbox by id: document.querySelector('#radio_1').checked = true; // Check checkbox by value: document.querySelector('#type > [value="1"]').checked = true; // If this is the only input with a value of 1 on the page, you can leave out the #type > document.querySelector('[value="1"]').checked = true; <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>

得到的值:

$("[name='type'][checked]").attr("value");

设置的值:

$(this).attr({"checked":true}).prop({"checked":true});

单选按钮单击add attr checked:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});