January 13th, 2006
Mass Toggle Checkboxes with Javascript
A quick way to toggle a list of checkboxes is to assign a CSS class to the checkboxes that you wish to change and use some javascript to toggle them. The following example requires the javascript library bundled with Prado.
Example, consider the following list of checkboxes and a button to toggle their checked state
<com:TCheckBoxList> <com:TListItem class="toggable" Text="One" value="1" /> <com:TListItem class="toggable" Text="Two" value="2" /> <com:TListItem class="toggable" Text="Three" value="3" /> <com:TListItem class="toggable" Text="Four" value="4" /> <com:TListItem class="toggable" Text="Five" value="5" /> <com:TListItem class="toggable" Text="Six" value="6" /> </com:TCheckBoxList> <com:TButton ID="button1" Text="Toggle" />
Notice that we have added a CSS class “toggable” to each of the list items. We will use this to find all the elements with that particular CSS class in the following javascript.
<script type="text/javascript"> //<![CDATA[ /** * @param string CSS class name of elements to toggle */ function toggle_checkboxes(cssClass) { var elements = document.getElementsBySelector(cssClass); elements.each(function(checkbox) { checkbox.checked = !checkbox.checked; }); } var button1 = $("<%= $this->Page->button1->ClientID %>"); Event.observe(button1, "click", function(ev) { toggle_checkboxes(".toggable"); Event.stop(ev); }); //]]> </script>
The toggle_checkboxes function iterates through a list of elements with corresponding CSS class name and change the checked state.
var elements = document.getElementsBySelector(cssClass);
The function document.getElementsBySelector() returns a list of elements with given CSS class name.
elements.each(function(checkbox) { // your code here });
Since elements is a javascript array, the each function allows you to iterate the array. The each function is analogous to the foreach construct in PHP
foreach($elements as $checkbox) { //your code here }
To intercept a click event on the button, we can use the Event.observe() function. It takes 3 parameters, the 1st is either a string of the button ID or the button element itself. The 2nd parameter is the name of the event to observer/register, in this case, click. The last and 3rd parameter is a javascript function. Here we simply declare the function in place as the 3rd parameter.
After the button is clicked, and the checkboxes are toggled, we need to stop further events in the button. To do this, the function Event.stop() can be used, it takes a DOM Event as only parameter.
Last thing to do is to register the javascript library in the page php class. E.g.
protected function onPreRender($param) { $this->registerClientScript("dom"); }
See example: Toggle checkboxes
Lots of fun with javascript!