简体   繁体   English

通过选中和取消选中复选框来从数组中添加和删除值

[英]Adding and removing values from array by checking and unchecking checkboxes

The following code adds checkbox values to an array when checkboxes are checked. 选中复选框后,以下代码将复选框值添加到数组。 How can I change this so that a checkbox's value is removed from the array when a checkbox is unchecked? 如何更改此设置,以便在未选中复选框的情况下从数组中删除复选框的值?

var departments = [];
$("input[name='department_pk[]']").change(function() {
        $("input[name='department_pk[]']:checked").each(function(i){
          departments[i] = $(this).val();
        }); 
}); 

The problem is you are not removing the previously selected items from the array. 问题是您没有从阵列中删除先前选择的项目。 Assume you have selected 5 items now in the array you have data for indexes 0 to 4, then you are unselecting 2 items now your each loop will reset the indexes 0 to 2 but the indexes 3 and 4 is still present in the array. 假设您现在在数组中选择了5个项目,索引0到4的数据,然后取消选择2个项目,现在每个循环将索引0重置为2,但是数组中仍然存在索引3和4。 that is the problem. 那就是问题所在。

A better solution will be is to create a fresh array using .map() 更好的解决方案是使用.map()创建一个新数组

var departments = [];
$("input[name='department_pk[]']").change(function () {
    departments = $("input[name='department_pk[]']:checked").map(function (i) {
        return $(this).val();
    }).get();
});

I would clear the array first before you add new elements to it. 在向其中添加新元素之前,我将先清除该数组。

var departments = [];
$("input[name='department_pk[]']").change(function() {
    departments = [];
    $("input[name='department_pk[]']:checked").each(function(i){
      departments[i] = $(this).val();
    }); 
}); 
check this..
var departments = [];
    $("input[name='department_pk[]']").change(function() {
            $("input[name='department_pk[]']").each(function(i){
              if(jQuery(this).is(":checked")) {
                 departments[i] = $(this).val();
               } else {
                  departments[i] = 0;
               }
            }); 
    });

This sort of worked, but map() is more accurate: 这种工作方式,但是map()更准确:

          if($(this).is(':checked')) {
    departments.push($(this).val());
  } else {
    departments.pop($(this).val());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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