我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我们可以检查$_POST/Request元素是否有它。然后将它赋值给一个变量。
$value = (null !== $_POST['checkboxname']) ?“是”:“不是”;
这与isset()函数非常相似。但是isset()函数不能用于表达式的结果。我们可以用null检查它的结果,并达到相同的效果。
最后的值只是虚数。如果所需字段为布尔类型,我们可以将“YES”更改为1,将“NO”更改为0。
其他回答
当提交时复选框未选中时,将复选框的值更新为'NO'并设置checked = 'TRUE'
https://jsfiddle.net/pommyk/8d9jLrvo/26/
$(document).ready(function()
{
function save()
{
if (document.getElementById('AgeVerification').checked == false)
{
document.getElementById('AgeVerification').value = 'no';
document.getElementById('AgeVerification').checked = true;
}
}
document.getElementById("submit").onclick = save;
})
有一个更好的解决办法。 首先,只向选中的复选框提供name属性。 然后点击提交,通过JavaScript函数检查所有未选中的框。 当你提交时,只有那些会在表单集合中检索到那些有name属性的。
//removing name attribute from all checked checkboxes
var a = $('input:checkbox:checked');
$(a).each(function () {
$(this).removeAttr("name");
});
// checking all unchecked checkboxes
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).attr("checked", true);
});
优势: 不需要创建额外的隐藏框,并操作它们。
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });
I see this question is old and has so many answers, but I'll give my penny anyway. My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
这样你会得到一个像这样的$_POST数组:
Array
(
[field1] => 1
[field2] => 0
)