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:19
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');
查看更多
裙下三千臣
3楼-- · 2018-12-31 13:20

Yes, it worked for me like a way:

$("#radio_1").attr('checked', 'checked');
查看更多
明月照影归
4楼-- · 2018-12-31 13:21

We should want to tell it is a radio button.So please try with following code.

$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
查看更多
柔情千种
5楼-- · 2018-12-31 13:23

For versions of jQuery equal or above (>=) 1.6, use:

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

For versions prior to (<) 1.6, use:

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

Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.

查看更多
时光乱了年华
6楼-- · 2018-12-31 13:24

Try this with example

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>


<script>
$(document).ready(function () {
    $('#myForm').on('click', function () {
        var value = $("[name=radio]:checked").val();

        alert(value);
    })
});
</script>
查看更多
人气声优
7楼-- · 2018-12-31 13:25

I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.

Example is in here:

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

查看更多
登录 后发表回答