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

其他回答

jQuery 1.6中添加了另一个函数prop(),用于相同的目的。

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

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

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

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

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

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

如果属性名称不起作用,不要忘记id仍然存在。这个答案是给那些想知道你怎么做的人的。

$('input[id=element_id][value=element_value]').prop("checked",true);

因为属性名对我没用。请确保id和名字周围没有双引号或单引号。

干杯!

试试这个

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

if选中返回True 如果未选中则返回False

jQuery v1.10.1

使用prop()方法

来源链接

<p>
    <h5>Radio Selection</h5>

    <label>
        <input type="radio" name="myRadio" value="1"> Option 1
    </label>
    <label>
        <input type="radio" name="myRadio" value="2"> Option 2
    </label>
    <label>
        <input type="radio" name="myRadio" value="3"> Option 3
    </label>
</p>

<p>
    <button>Check Radio Option 2</button>
</p>


<script>
    $(function () {

        $("button").click(function () {
            $("input:radio[value='2']").prop('checked',true);
        });

    });
</script>