首页 > 解决方案 > 从多组复选框中向数组添加和删除复选框值

问题描述

我正在处理下面的代码。如何将复选框组中的值添加和删除到数组中?

显然,我可以在选中复选框时添加值,但我尝试在取消选中复选框时删除相同的值没有奏效!

 
 let opts = [];
 $('input:checkbox[name=a]').on('change', function(){
  if($(this).is(':checked')){
       let val = $(this).data('shape');
        opts.push(val);
        console.log(opts);
       }
       else{
                let val = $(this).data('shape');
       opts.filter(a => a !== val);
       console.log(opts);
       }
  
});

 $('input:checkbox[name=b]').on('change', function(){
  if($(this).is(':checked')){
       let val = $(this).data('shape');
        opts.push(val);
        console.log(opts);
       }
       else{
         let val = $(this).data('shape');
       opts.filter(a => a !== val);
       console.log(opts);
       }
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" data-shape="scb1" />
<input type="checkbox" name="a" data-shape="scb2"  />
<input type="checkbox" name="a" data-shape="scb3"  />
<input type="checkbox" name="a" data-shape="scb4" />


<input type="checkbox" name="b" data-shape="mcb1"  />
<input type="checkbox" name="b" data-shape="mcb2"  />
<input type="checkbox" name="b" data-shape="mcb3"  />
<input type="checkbox" name="b" data-shape="mcb4"  />

标签: javascriptjquery

解决方案


let opts = [];
 $('input:checkbox[name=a],[name=b]').change(function(){

  let val = $(this).data('shape');
  
  if($(this).is(':checked'))
  {      
        opts.push(val);
        console.log(opts);
       }
       else
       {         
         opts.splice( $.inArray($(this).data('shape'), opts), 1 );
         console.log(opts);
       }  
   });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" data-shape="scb1" > First </input><br>
<input type="checkbox" name="a" data-shape="scb2"  > Second </input><br>
<input type="checkbox" name="a" data-shape="scb3"  > Three</input><br>
<input type="checkbox" name="a" data-shape="scb4" > Four</input><br>
<br>

<input type="checkbox" name="b" data-shape="mcb1"  >Five</input><br>
<input type="checkbox" name="b" data-shape="mcb2"  >Six</input><br>
<input type="checkbox" name="b" data-shape="mcb3"  >Seven</input><br>
<input type="checkbox" name="b" data-shape="mcb4"  >Eight</input><br>


推荐阅读