使用全选验证删除选中的复选框项目


Delete selected checkbox items with select all validation

我有一个项目列表,生成为:

<input type="checkbox" name="sacb" onchange="selAll();" title="select all"/>
  <?php
  while($row = mysql_fetch_array($res)){
    echo "<div><input type='checkbox' name='cb' value='$row[id]'>$row[item]</div>";
  }
?>

脚本

function selAll(){
  var s = document.form.sacb;
  var t = document.form.cb;
  for(var i=0; i<t.length; i++){
    t[i].checked = s.checked;
  }
}

这可以很好地选择/取消选择所有复选框。

我想提交此表单,其中要删除多个/所有选定项目。但我并没有得到所有选中的复选框。我已经搜索并发现我需要将我的PHP代码替换为:

<input type='checkbox' name='cb[]' value='$row[id]'>$row[item]

但一旦我这样做,脚本就无法选中所有复选框。如何解决这个问题?有什么解决方案吗?

您不能使用点表示法来访问名称中带括号的元素,因此您必须使用元素集合来检索它们

function selAll(){
    var s = document.form.sacb;
    var checkboxes = document.form.elements['cb[]'];
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = s.checked;
    }
}

您可以从下面的javascript 中更新选中的复选框

请添加您的代码来选择所选数组的数量,以获得简单的javascript在这个例子中,我使用jquery来获取复选框的数组,并检查它是否被选中

var field, fields = $('.edit_user_notifi :checkbox'), i = fields.length;
        var notification_status = '';
        while (i--) {
            field = fields[i];
            if(notification_status == '')
            {
                if (field.checked) {
                    notification_status = field.id+'~1';
                } else {
                    notification_status = field.id+'~0';
                }
            }else{
                if (field.checked) {
                    notification_status = notification_status +','+ field.id+'~1';
                }else{
                    notification_status = notification_status +','+ field.id+'~0';
                }
            }
        }

只需更改一些小逻辑,就可以使用简单的javascript,或者如果使用jquery,那么if将很好。