Checkbox + JQuery Pattern

We were working on a project which includes multiple selection entries under multiple categories. All the checkboxes are dynamically generated (Database lookup) since those were master items maintained by the admins of the system. We were able to easily generate the checkboxes by bringing in data using JSON and dynamically appending checkboxes to a DIV using JQuery. Now the problem was to get all the selected entries per category. That is when we brought in the following pattern by which a good naming convention followed by the amazing power of Jquery came into play. We made sure that all our check boxes followed a particular pattern like chk+category+id(the primary id). And then wrote the function given below to get the selected items in a particular category.

function GetCheckedItems(item)
    var strIDList="";   
    //this is the pattern: the class is going to be the checkboxtype followed by checkbox ex. contactcheckbox
    //so to get the generalized checkbox typ replace the checkbox with ""
    //this would give us just .contact. so taking the substring from 1 which would give us contact
    var strSearch=item.toString().replace(('checkbox'),'').substring(1);  
    //now prefixing chk to it so that we get the checkbox name
    //alert (strSearch);
            if ($(this).is(":checked"))
                //replacing the chk followed by the checkbox type to get the IDs
                strIDList+=$(this).attr("id").replace((strSearch),"") + ",";
    //getting the length to negate the last ,
    var strLength=strIDList.length - 1;
    return strIDList.substring(0,strLength);

Hope this helps.

Happy Programming!!!



0 Responses to “Checkbox + JQuery Pattern”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: