javascript tutorial - [Solved-5 Solutions] How to check a radio button with jQuery ? - javascript - java script - javascript array



Problem:

We 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>
click below button to copy the code. By JavaScript tutorial team

And the JavaScript:

jQuery("#radio_1").attr('checked', true);
click below button to copy the code. By JavaScript tutorial team

Doesn't work:

jQuery("input[value='1']").attr('checked', true);
click below button to copy the code. By JavaScript tutorial team

Doesn't work:

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
click below button to copy the code. By JavaScript tutorial team

Doesn't work: Do we have another idea? What am WE missing?

Solution 1:

	$("#radio_1").prop("checked", true)
click below button to copy the code. By JavaScript tutorial team

For versions of jQuery prior to 1.6, use:

$("#radio_1").attr('checked', 'checked');
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Try this. In this example, I'm targeting it with its input name and value

$("input[name=background][value='some value']").prop("checked",true);

click below button to copy the code. By JavaScript tutorial team

Solution 3:

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

$("#radio_1").prop("checked", true); 
click below button to copy the code. By JavaScript tutorial team

Solution 4:

Short and easy to read option:

$("#radio_1").is(":checked")
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Try this. To check Radio button using Value use this.

$('input[name=type][value=2]').attr('checked', true); 
click below button to copy the code. By JavaScript tutorial team

or

$('input[name=type][value=2]').attr('checked', 'checked');
click below button to copy the code. By JavaScript tutorial team

or

$('input[name=type][value=2]').prop('checked', 'checked');
click below button to copy the code. By JavaScript tutorial team

To check Radio button using ID use this.

$('#radio_1').attr('checked','checked');
click below button to copy the code. By JavaScript tutorial team

or

$('#radio_1').prop('checked','checked');
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - How to check a radio button with jQuery ?