I am working on the below code. How can I add and remove value from checkbox groups into an array?
Apparently I am able to add the values on checking the checkbox but my attempts to remove same value on un-checking the checkbox didn't work!
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" />