views:

229

answers:

2

I have a bunch of checkboxes that are created dynamically on page load and written like so:

<input type='checkbox' name='quicklinkscb' id='quicklinkscb_XX'/>

where XX represents the id of the item from the database.

I want to be able to parse the page via javascript for all checkboxes and:

find their id and strip the 'quicklinksscb_' from it and:

if(checkbox is checked)
{
  add to add list
}
else
{
 add to remove list
}

I can't do this via checkbox list and I want to do this all client side

Can someone shed some light

+4  A: 
for(var i = 0; i < document.forms.length; i++) {
    for(var j = 0; j < document.forms[i].elements.length; j++) {
        var elem = document.forms[i].elements[j];
        if(elem.type == 'checkbox')
            var tag = elem.getAttribute('id');
            tag.replace(/^quicklinkscb_/, '');
            if(elem.checked)
                add_to_add_list(tag);
            else
                add_to_remove_list(tag);
    }
}

Vastly easier in jQuery:

$(':checkbox').each(function() {
    var tag = $(this).attr('id');
    tag.replace(/^quicklinkscb_/, '');
    if($(this).attr('checked'))
        add_to_add_list(tag);
    else
        add_to_remove_list(tag);
});
chaos
Why not use `document.getElementsByTagName('input')`, and check each one for `type == 'checkbox'` instead?
aditya
+1  A: 

While not disputing that the jQuery code sample shown by chaos is shorter and easier to read than the POJ sample, I would question the justification of using the multi-Kb jQuery library for just this application.

My POJ version would follow aditya's suggestion as follow:

var 
  add_list = [],
  del_list = [];

for (var inputs = document.getElementsByTagName ('input'), cb, i = inputs.length;
     i--;)
  if ((cb = inputs[i]).type === 'checkbox') {
    cb.id = cb.id.replace (/^quicklinkscb_/, '');
    (cb.checked ? add_list : del_list).push (cb);
  }

I read the original question as asking that the checkbox id's be changed and then elements be added to add/delete lists. The equivalent of chaos's implementation would be this :

for (var inputs = document.getElementsByTagName ('input'), cb, i = inputs.length;
         i--;)
  if ((cb = inputs[i]).type === 'checkbox')
    (cb.checked ? add_list : del_list).push (cb.id.replace ((/^quicklinkscb_/, '')));
Hans B PUFAL