我尝试用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=type]").val(['1']);

http://jsfiddle.net/nwo706xw/

其他回答

试试这个

$(document).ready(function(){
    $("input[name='type']:radio").change(function(){
        if($(this).val() == '1')
        {
          // do something
        }
        else if($(this).val() == '2')
        {
          // do something
        }
        else if($(this).val() == '3')
        {
          // do something
        }
    });
});

Attr接受两个字符串。

正确的做法是:

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

短而易读的选项:

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

它返回true或false,所以你可以在if语句中使用它。

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

示例如下:

$(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/

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