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

不工作:

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


当前回答

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

其他回答

试试这个:

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

我们应该告诉它是单选按钮。所以请尝试以下代码。

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);

我有一些相关的例子要增强,如果我想添加一个新的条件,比如说,如果我想要隐藏配色方案后,我点击项目状态值除摊铺机和铺路板。

示例如下:

$(function () {
    $('#CostAnalysis input[type=radio]').click(function () {
        var value = $(this).val();

        if (value == "Supply & Lay") {
            $('#ul-suplay').empty();
            $('#ul-suplay').append('<fieldset data-role="controlgroup"> \

http://jsfiddle.net/m7hg2p94/4/

Attr接受两个字符串。

正确的做法是:

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

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

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