我有一组复选框控件,我想为已选中的值发布一个值,而对于数组中未选中的值,则为null
我在下面编写了代码片段,但无论检查状态如何,我总是得到相同的值
$("#bt1").click(function() {
var checked = []
var val = ''
var $chbx = $("input[name='advsrc']")
$chbx.each(function() {
if ($chbx.is(':checked')) {
val = 'ahmad'
} else {
val = 'null'
}
checked.push(val);
});
console.log(checked)
return false;
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="bt1" type="button" value="button" />
<input id="grndsrc" type="checkbox" checked="checked" name="advsrc" />
<input id="fnamesrc" type="checkbox" name="advsrc" />
<input id="lnamesrc" type="checkbox" name="advsrc" />
<input id="dobsrc" type="checkbox" name="advsrc" />
<input id="telsrc" type="checkbox" name="advsrc" />
<input id="ssnsrc" type="checkbox" name="advsrc" />
&#13;
@ techlove的回答
$("#bt1").click(function() {
var checked = []
var val = ''
var $chbx = $("input[name='advsrc']")
$chbx.each(function() {
if ($(this).attr("checked")) {
val = 'ahmad'
} else {
val = 'null'
}
checked.push(val);
});
console.log(checked)
return false;
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="bt1" type="button" value="button" />
<input id="grndsrc" type="checkbox" name="advsrc" />
<input id="fnamesrc" type="checkbox" name="advsrc" />
<input id="lnamesrc" type="checkbox" name="advsrc" />
<input id="dobsrc" type="checkbox" name="advsrc" />
<input id="telsrc" type="checkbox" name="advsrc" />
<input id="ssnsrc" type="checkbox" name="advsrc" />
&#13;
答案 0 :(得分:1)
您的问题在这一行:
if ($chbx.is(':checked')) {
将该行更改为:
if ($(this).is(':checked')) {
您可以使用.each()或.map()代替Array.prototype.reduce(),以获得所需的结果。请务必使用.get()检索 $(&#34 ;: checkbox [name =&#39; advsrc&#39;]&#34;)匹配的元素。
$("#bt1").click(function() {
var checked = $(":checkbox[name='advsrc']").map(function(idx, ele) {
return (ele.checked) ? 'ahmad' : 'null';
}).get();
console.log(checked);
return false;
})
$("#bt2").click(function() {
var checked = $(":checkbox[name='advsrc']").get().reduce(function(acc, ele, idx) {
acc[ele.id || 'noId' + idx] = (ele.checked) ? 'a' : '';
return acc;
}, {});
console.log(checked);
return false;
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="bt1" type="button" value="button" />
<input id="bt2" type="button" value="buttonNew" />
<input id="grndsrc" type="checkbox" checked="checked" name="advsrc" />
<input id="fnamesrc" type="checkbox" name="advsrc" />
<input id="lnamesrc" type="checkbox" name="advsrc" />
<input id="dobsrc" type="checkbox" name="advsrc" />
<input id="telsrc" type="checkbox" name="advsrc" />
<input id="ssnsrc" type="checkbox" name="advsrc" />
<input type="checkbox" name="advsrc" />
&#13;