jQuery Set RadioButton to be Checked


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

jQuery Set RadioButton to be Checked

Here we look at how to use jQuery to set an ASP.NET RadioButton control to be checked.

RadioButton doesn't Postback

The reason I've had to do this in jQuery was that I came across a situation where I have a group of RadioButton's outside of an UpdatePanel, they are all set for AutoPost = 'true', and they all call the same method for the CheckedChanged event. I set some AsyncPostBackTriggers so that they cause the UpdatePanel to update, they update a repeater's data results inside the UpdatePanel. Now this all works fine, until I want to set one of the RadioButtons to be checked by default on PageLoad. Now the RadioButton which is checked by default on PageLoad no longer posts back to the server, I even checked with Fiddler to watch the internet traffic, and nothing is happening with that RadioButton, though the other ones are fine.

So as a fix for this, I've used jQuery to make the RadioButton to be checked, instead of doing it the C# code, and now everything works fine.

jQuery Set RadioButton to be Checked Example

Right so firstly I use the $(document).ready(handler) method to ensure the page has loaded and all the .NET controls will be on the page. Then I use the .ClientID property of the .NET control to help obtain the correct ID of the ASP.NET RadioButton control (.NET 3.5). That is enough to get jQuery to find the control, so next up we call the jQuery .attr(attributeName, value) method which allows us to set attributes on the element, in this case we set the 'checked' attribute to become 'checked', and voila, our RadioButton will now be checked when the page first loads.


  $(document).ready(function() {
    $('#' + '<%=RadioButton_GreenCars.ClientID %>').attr('checked', 'checked');
  });