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

不工作:

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


当前回答

为了防止有人在使用jQuery UI时试图实现这一点,你还需要刷新UI复选框对象以反映更新后的值:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set

其他回答

对于jQuery等于或高于(>=)1.6的版本,请使用:

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

对于(<)1.6之前的版本,使用:

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

提示:您可能还想随后在单选按钮上调用click()或change()。查看评论了解更多信息。

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

我使用这个代码:

我为英语感到抱歉。

var $j = jQuery.noConflict(); $j(function() { // add handler $j('#radio-1, #radio-2').click(function(){ // find all checked and cancel checked $j('input:radio:checked').prop('checked', false); // this radio add cheked $j(this).prop('checked', true); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset class="section"> <legend>Radio buttons</legend> <label> <input type="radio" id="radio-1" checked> Option one is this and that&mdash;be sure to include why it's great </label> <br> <label> <input type="radio" id="radio-2"> Option two can be something else </label> </fieldset>

试试这个

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

是的,这对我来说很管用:

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