Parse page for checkboxes via javascript

孤街醉人 提交于 2019-12-11 06:43:22

问题


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


回答1:


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);
});



回答2:


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_/, '')));


来源:https://stackoverflow.com/questions/1183419/parse-page-for-checkboxes-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!