简体   繁体   中英

Problem selecting multiple checkboxes

I am using a checkbox that has the name as "selectedids[]" and I am trying to select all checkboxes with the JavaScript. The code is not working. When I change the name of the checkbox to "selectedids" it works, but I can't do so because I need all the ids that are selected on the POSTED page.

The checkbox is as follows:

foreach($rows as $row)
{
<input type="checkbox" name="selectedids[]" value="<?php echo $row['id']; ?>" class="checkbox" />
........
........
}

And the Java-script function is as follows:

function SetAllCheckBoxes(CheckValue)
{
    var CheckValue=true;
    if(!document.forms['main'])
        return;
    var objCheckBoxes = document.forms['main'].elements['selectedids[]'];
    if(!objCheckBoxes)
        return;
    var countCheckBoxes = objCheckBoxes.length;
    if(!countCheckBoxes)
        objCheckBoxes.checked = CheckValue;
    else
        // set the check value for all check boxes
        for(var i = 0; i < countCheckBoxes; i++)
            objCheckBoxes[i].checked = CheckValue;
}

Please help me......

Thanks in advance.......

Do you have the option to use jQuery? If so, then you could do something like:

$(':checkbox').each(function(){
  $(this).attr('checked',true);
});

It also might work to try:

$(':checkbox').attr('checked',true);

Or, if you just want to make sure all the boxes are checked only when the page first loads you could have your php that creates the checkboxes include "CHECKED". ie

<input type='checkbox' name='selectedids[]' value='value' CHECKED>

Updated to use :checkbox per comment

Why don't you just select them by id? eg

var a=0;
while(document.getElementById('mycheckbox_'+a))document.getElementById('mycheckbox_'+a).checked=true;

If it was me, I would use the class of the checkboxes to identify them, with a bit of jQuery. This would work:

$('input.checkbox').each(function(){$(this).attr('checked',true);   });

It would set all checkboxes with class "checkbox" as true.


Beaten to it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM