Checking / Unchecking radio buttons and retrieving their value in jQuery

Let us assume we have radio buttons

<input name="rd_name" id="RD1" value="Value One" /> Label 1
<input name="rd_name" id="RD2" value="Value Two" /> Label 2

To retrieve and set radio button values by id we have the following methods. To retrieve we have,

window.alert($("#RD1").val())

and to set the value by id we have

$("#RD1").val('New Value for One')

To check if a paticular button is checked or not we have,

window.alert($("#RD1").attr('checked'))

and to set the status of button to checked or unchecked we can do

$("#RD1").attr("checked", "checked");

Additionaly, to remove a checked status from a radio button we can do

$("#RD1").removeAttr("checked");

Okay, now to perform the above actions by name attribute of the radio button we can do the following.

To print the value of checked radio button

window.alert($('input[name=rd_name]:checked').val());

To set the value of checked input field

$('input[name=rd_name]:checked').val('New value of checked button');

To set the status of a radio button to checked we can do something like the following. Here 0(zero) is the position of first radio button element.

$('input[name="rd_name"]')[0].checked = true;

Leave a Reply