Wednesday, March 05, 2014

Web Forms: Radio and Checkbox List Javascript Selection / Checked Manipulation

Yes, I know web forms aren't cool and all the hip kids are using MVC. Some of us are stuck enhancing existing applications (I don't want to call applications that bring in 100's of thousands of dollars "legacy").

Anyway, here is the scenario.  I've got a checkboxlist control.  I also have a radiobuttonlist with two entries, "All" and "None".  When I click on the radiobuttonlist I want to either check all the items in the checkboxlist control or uncheck all the items in the checkboxlist control.  I also wanted the checkboxlist control set so once individual items are checked the two options in the radiolistbuttonlist to be deselected / unchecked. I'm using Telerik controls so I can use a limited subset of jQuery, so I used it.

Step 1: Code Behind

On my page load I did this-

     ListItem lst1 = new ListItem ( Classes.Utility.Translate ( "AllLabel" ), "A" );  
     ListItem lst2 = new ListItem ( Classes.Utility.Translate ( "NoneLabel" ), "N" );  
     lst1.Attributes.Add ( "onclick", "SetClear(true)" );  
     lst2.Attributes.Add ( "onclick", "SetClear(false)" );  
     rdoOptions.Items.Add ( lst1 );  
     rdoOptions.Items.Add ( lst2 );  
     chkList.Attributes.Add ( "onclick", "return ClearRadioButtonList()" );  

The translate stuff don't worry about.  Just the way I do translation on the fly (for another post).  Note if you set the onclick event for each item or for all items by setting the onclick for the control rather than the items.

Step 2: Client Side

Here are a few Javascript functions I added-

  function ClearRadioButtonList() {  
     $("#<%= rdoOptions.ClientID %> input[type=radio]").prop('checked', false);  
    function SetClear(b) {  
     $("#<%= chkList.ClientID %> input[type=checkbox]").prop('checked', b);  

And it works!  I hope this helps someone.  These two pages were helpful to me figuring this out-

No comments: