How to check a radio button with jQuery?

2018-12-31 12:23发布

I try to check a radio button with jQuery. Here's my code:

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

And the JavaScript:

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

Doesn't work:

jQuery("input[value='1']").attr('checked', true);

Doesn't work:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work:

Do you have another idea? What am I missing?

27条回答
心情的温度
2楼-- · 2018-12-31 13:07
function rbcitiSelction(e) {
     debugger
    $('#trpersonalemail').hide();
    $('#trcitiemail').show();
}

function rbpersSelction(e) {
    var personalEmail = $(e).val();
    $('#trpersonalemail').show();
    $('#trcitiemail').hide();
}

$(function() {  
    $("#citiEmail").prop("checked", true)
});
查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 13:08

Try This:

$(document).ready(function(){
  $("#Id").prop("checked", true).checkboxradio('refresh');
});
查看更多
泛滥B
4楼-- · 2018-12-31 13:09

Short and easy to read option:

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

It returns true or false, so you can use it in "if" statement.

查看更多
皆成旧梦
5楼-- · 2018-12-31 13:09

The $.prop way is better:

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

and you can test it like the following:

$(document).ready(function () {                            
    $("#radio_1, #radio_2", "#radio_3").change(function () {
        if ($("#radio_1").is(":checked")) {
            $('#div1').show();
        }
        else if ($("#radio_2").is(":checked")) {
            $('#div2').show();
        }
        else 
            $('#div3').show();
    });        
});
查看更多
只若初见
6楼-- · 2018-12-31 13:11

Try this

var isChecked = $("#radio_1")[0].checked;
查看更多
泪湿衣
7楼-- · 2018-12-31 13:13

Some times above solutions do not work, then you can try below:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

Another way you can try is:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);
查看更多
登录 后发表回答