J. Cornelius

JavaScript Checkbox Magic Using Prototype

January 2, 2007

As common or rare as it may be for someone to need the ability to select and deselect checkboxes in a form, here is a way to do it using the Prototype JavaScript Library. I recently needed a way to do this for the Private Message functionality of a Web Application I'm working on. The example code below is taken from this Application.

First make the Event observers:

if($('box_list') != null) { Event.observe($('checkall'),'click',pm_checkall,true); Event.observe($('clearall'),'click',pm_clearall,true); Event.observe($('checkread'),'click',pm_checkread,true); Event.observe($('checkunread'),'click',pm_checkunread,true); }

Then make the functions to handle selecting and deselecting the checkboxes. Here I've made a function to loop over all the form elements and operate on the ones we want to change; and 4 functions that tell the main function what to do based on the Event observed:

function pm_checkall(e) { pm_check_uncheck(true); } function pm_clearall(e) { pm_check_uncheck(false); } function pm_checkread(e) { pm_check_uncheck(false,"unread"); pm_check_uncheck(true,"read"); } function pm_checkunread(e) { pm_check_uncheck(false,"read"); pm_check_uncheck(true,"unread"); } function pm_check_uncheck(val,group) { lst = document.forms['box_list']; len = lst.elements.length; var i=0; for(i=0; i<len ; i++) { if(group) { if(lst.elements[i].className == group) { lst.elements[i].checked = val; } } else { if(lst.elements[i].type == "checkbox") { lst.elements[i].checked = val; } } } }

Now it's time to add the correct markup to the page. I use Smarty for templates so the markup below shows the foreach loop where I generate the checkboxes for each message.

<form id="box_list" action="/messages/action/" method="post"> <table id="private_message_list"> {foreach from=$message_list key=key item=message} <tr> <td><input type="checkbox" name="m[{$key}]" value="1" class="{$message.status}" /></td> <td><a href="/messages/view/{$key}/" class="{$message.status}">{$message.subject}</a></td> <td>{$message.author_name}</td><td>{$message.created_on|date_format}</td> </tr> {/foreach} </table> <div id="checkopt"> Select: <span id="checkall">All</span> <span id="clearall">None</span> <span id="checkread">Read</span> <span id="checkunread">Unread</span> </div>

This is a rather clean and simple way to accomplish what was a somewhat difficult task.

Was it good for you?

Post to Digg Post to del.icio.us Post to ma.gnolia Post to Furl Post to Mixx

Tags

development, howtos, javascript, prototype

About

J Cornelius is a software developer, Web developer, and Formula 1 fan in Atlanta GA. He has a strange affinity for odd numbers, european sports cars, thoughtful analogies, and is hopelessly addicted to chips & salsa. Read more

Recent Articles