Wednesday, September 30, 2009

using the Prototype JavaScript Library its really magic, #php, #cakephp, #opensource, #JavaScript library

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 {
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.



{foreach from=$message_list key=key item=message}





{/foreach}
{$message.subject} {$message.author_name}{$message.created_on|date_format}


Select:
All
None
Read
Unread

No comments:

Post a Comment