我试图设置复选框的
下面的代码对于文本有效,当选中或取消选中复选框时,文本会更改,但是当复选框未被选中时,提交到数据库的值是
value
,如果选中,value
是active
,但如果未选中,则为disabled
。下面的代码对于文本有效,当选中或取消选中复选框时,文本会更改,但是当复选框未被选中时,提交到数据库的值是
null
。
HTML
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == false) {
text.style.display = "inline";
document.getElementById('checkbox').value = "active";
} else {
text.style.display = "none";
document.getElementById('checkbox').value = "disable";
}
}
当复选框未选中时,我期望在数据库中发布的值为 disabled
,但目前得到的是 null
。
更新:
根据提供的答案反馈,添加了包括AJAX
调用的修复版本。这只是为了以防万一有人遇到相同的问题。
如果你在serialize()文档底部的示例中尝试,你会发现未选中的复选框没有被附加上值。你需要手动添加。也许这可以帮助你:如何覆盖jquery的.serialize()以包括未选中的复选框
HTML
<form method="post" class="add_sub_categories">
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
<a class="btn btn-xs btn-info save_main_cat">GO!</a>
</form>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == true) {
text.style.display = "inline";
} else {
text.style.display = "none";
}
}
AJAX
$(document).ready(function() {
$(".save_main_cat").click(function() {
var data = $('.add_main_categories').serialize();
/* This code will include the value for the checkbox when unchecked */
$(".add_main_categories input:checkbox:not(:checked)").each(function(e) {
data += "&"+this.name+'=disable';
});
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/categories_ajx/update_main_categories",
data: data,
success: function() {
$('#addCat').modal('hide');
$(".add_main_categories")[0].reset();
dttable.destroy();
$(document).ready(function() {
main_cat(), main_cat_option(), dt_tables();
});
}
});
});
});
name
和id
是相同的。2)您已经有了一个变量checkBox
。在if/else
语句中没有理由再次获取它。使用该变量即可。3)您正在切换true/false
值。如果为false
(未选中),则该值现在为“active”。应进行切换。4)display:Active
不是有效的样式。 - Rob Scott