Nov 12, 2010

jQuery: Common Operations on Radio Button & Checkbox

This article shows how you can set and retrieve value of radio button and checkbox using jQuery.

Radio Button:

See following example for radio button:


Select the most applicable option

<input type="radio" name="applicable" id="applicable1"  value="Option1"/>Option1  
<input type="radio" name="applicable" id="applicable2" value="Option2"/>Option2  
<input type="radio" name="applicable" id="applicable3" value="Option3"/>Option3
<input id="btnShow" type="button" value="Show" />
<input id="btnAssign" type="button" value="Assign" />
$("#btnShow").click(function() {
            alert($('input[name=applicable]:checked').val());
        });

$("#btnAssign").click(function() {
            var valApplicable = "Option1";
            $('[name="applicable" ][value="' + valApplicable + '"]').attr('checked', true);
        });

When user clicks on Show button, It will show value of selected option. The main tricky part is to assign value to radio button means you have value and you need to set true corresponding radio button.In our example, When user clicks on Assign button, First option will be selected.

To get the selected value:

$('input[name=applicable]:checked').val();

To select radio button from value:

$('[name="applicable" ][value="' + valApplicable + '"]').attr('checked', true);

Checkbox:

See following example for checkbox:


<input type="checkbox"  name="applicable" id="chk"  value="Option1"/>Option1  

<input id="btnGet" type="button" value="Show" />
<input id="btnSet" type="button" value="Assign" />
$("#btnGet").click(function() {
        alert($('#chk').is(':checked'));
            alert($('#chk').attr('checked'));
        });
        
        $("#btnSet").click(function() {
            $("#chk").attr('checked', true);
        });

To see whether checkbox is checked:

$('#chk').is(':checked')

OR

$('#chk').attr('checked')

To set checkbox:

$("#chk").attr('checked', true);

Hope, It helps.