javascript - 从多组复选框中向数组添加和删除复选框值
问题描述
我正在处理下面的代码。如何将复选框组中的值添加和删除到数组中?
显然,我可以在选中复选框时添加值,但我尝试在取消选中复选框时删除相同的值没有奏效!
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" />
解决方案
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>
推荐阅读
- apple-push-notifications - Apple Wallet/Passbook 通知无法发送
- firebase - 防止在文档中写入任意字段的 Firestore 安全规则
- python-3.x - 当值变量发生变化时,如何刷新 Tk Scale 滑块位置?
- r - 使用 purrr 基于多个现有变量创建新的指标变量
- ruby - 如何在 ruby 上请求频道的视频
- python - SSL:CERTIFICATE_VERIFY_FAILED] 证书验证失败:无法获取本地颁发者证书 (_ssl.c:1108) Discord/python
- django - 如何在没有必需参数的情况下获取 URL
- python - 了解 numpy 形状
- html - 字体真棒图标名称
- authentication - 多资源控制 Keycloak