我想在选中和取消选中它时获取单个复选框的值。我目前正在从事Codeigniter FW。我在单击时获得复选框的值,但是在单击时无法获得未选中框的值。请帮帮我!!我的代码在下面。
<table>
<thead>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input name="feature" type="checkbox" id="10" value="10" />
</td>
<td>
<input name="feature" type="checkbox" id="11" value="11" />
</td>
<td>
<input name="feature" type="checkbox" id="12" value="12" />
</td>
<td>
<input name="feature" type="checkbox" id="13" value="13" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$("input:checkbox").change(function() {
var someObj = {};
someObj.fruitsGranted = [];
var feature , key;
$("input:checkbox").each(function() {
if ($(this).is(":checked")) {
key = someObj.fruitsGranted.push($(this).attr("feature"));
someObj.fruitsGranted.push($(this).attr("id"));
feature = $(this).attr("id");
//key = $(this).attr("feature");
}
});
alert("GRANTED: " + feature + " ok " + key);
});
</script>
答案 0 :(得分:1)
change
函数将对当前的复选框选中/取消选中执行。
因此,您可以在每个函数之前提取该信息
$("input:checkbox").change(function() {
var someObj = {};
someObj.fruitsGranted = [];
var feature , key;
// you may extract all info from $(this) here on check/uncheck
alert("Checked " + $(this).is(":checked"));
// your rest code
});
您可能正在尝试实现购物车之类的功能。简化逻辑
// Declare data variables outside
var someObj = {};
someObj.fruitsGranted = [];
// register event for all checkboxes
$("input:checkbox").change(function() {
var feature , key;
if ($(this).is(":checked")) {
// get key/value and push into declared object's array
// alert if needed : alert("GRANTED: " + feature + " ok " + key);
} else {
// on uncheck
// get key/value and remove from object's array
// alert if needed : alert("REVOKED: " + feature + " ok " + key);
}
});
答案 1 :(得分:0)
要查找未选中的复选框值,您可以尝试
<script type="text/javascript">
$("input:checkbox").change(function() {
var someObj = [];
$("input:checkbox").each(function() {
console.log($(this).prop('checked'));
if ($(this).prop('checked') === false) {
someObj.push({feature:$(this).attr('id'),key:$(this).val()});
}
});
console.log(someObj);
});
</script>