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

Try this.

To check Radio button using Value use this.

$('input[name=type][value=2]').attr('checked', true); 

Or

$('input[name=type][value=2]').attr('checked', 'checked');

Or

$('input[name=type][value=2]').prop('checked', 'checked');

To check Radio button using ID use this.

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

Or

$('#radio_1').prop('checked','checked');
查看更多
栀子花@的思念
3楼-- · 2018-12-31 13:01

attr accepts two strings.

The correct way is:

jQuery("#radio_1").attr('checked', 'true');
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 13:02

One more function prop() that is added in jQuery 1.6, that serves the same purpose.

$("#radio_1").prop("checked", true); 
查看更多
大哥的爱人
5楼-- · 2018-12-31 13:04

try this

 $("input:checked", "#radioButton").val()

if checked returns True if not checked returns False

jQuery v1.10.1
查看更多
ら面具成の殇う
6楼-- · 2018-12-31 13:05

Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
查看更多
深知你不懂我心
7楼-- · 2018-12-31 13:06

If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.

$('input[id=element_id][value=element_value]').prop("checked",true);

Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.

Cheers!

查看更多
登录 后发表回答