Check/UnCheck A RadioButton based on a CheckBox value using jQuery

The title is as amusing as the request I got recently from one of the users. He had a requirement where he had to Check/Uncheck or Select/Deselect an ASP.NET RadioButton based on the value of another ASP.NET CheckBox using client side code. I suggested him to do it using jQuery. The same solution will also work for HTML controls too. Here's how:


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


        $('#CheckBox1').click(


             function() {


                 $("input[type='radio']").attr('checked',


                 $('#CheckBox1').is(':checked'));


             });


    });


 


</script>


</head>


<body>


    <form id="form1" runat="server">


    <div>


        <asp:RadioButton ID="RadioButton1" runat="server" Checked="false" Text="UnCheckMe" />


        <asp:CheckBox ID="CheckBox1" runat="server" Text="ChkUnChkRadio" />


    </div>


    </form>


</body>


</html>







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Pieter said...

Hi, thanks for your post. I have a similar scenario, but now with checkboxes and radio buttons.

In a case where in asp.net the radio button is defined as selected (checked), I sometimes want to uncheck it with jQuery:
$('[class=subx]').slideUp(200).each(function () { $(this).find("input:checked").attr('checked', false) ;
});

This visually unchecks the checkboxes and radiobuttons with the appropriate class. However, when I then read in a postback the value of the radio button in ASP.NET:
selectValue = qAnswerList.SelectedValue;
I get the answer as if the radio button has not been cleared.
Any suggestions would be appreciated.
Pieter

Pieter said...

Hi, I found the solution to the problem above.
I have added an extra radio button with value 0, and style="display:none"
ListItem li = new ListItem("", "0");
li.Attributes.Add("style", "display:none");
qAnswerList.Items.Add(li);

Then I can set this hidden radio button when I need to clear the selection:

$('[class=subx'])').slideUp(200).each(function () {
$(this).find('input[type=radio]:eq(0)').attr('checked', true);
$(this).find("input:checkbox:checked").attr('checked', false);

This works wonderful!