我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
简单的答案。如果你的代码中有checked="checked"将其改为unchecked="unchecked"
所以你的文本应该是这样的:
输入类型=“复选框” 名称=“您选择的名称” 未选中=“未选中”
如果它不包含这个,你总是可以添加它
其他回答
我使用这个jQuery块,它将在提交时为每个未选中的复选框添加一个隐藏输入。它将保证您每次都为每个复选框提交一个值,而不会弄乱您的标记,并冒着忘记在稍后添加的复选框上执行此操作的风险。它也与您正在使用的任何后端堆栈(PHP、Ruby等)无关。
// Add an event listener on #form's submit action...
$("#form").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "0"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
一种常见的方法是在每个复选框中附带一个隐藏变量。
<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>
在服务器端,我们首先检测隐藏变量列表,对于每个隐藏变量,我们尝试查看相应的复选框条目是否提交到表单数据中。
服务器端算法可能是这样的:
for input in form data such that input.name endswith .hidden
checkboxName = input.name.rstrip('.hidden')
if chceckbName is not in form, user has unchecked this checkbox
上面并没有完全回答这个问题,但是提供了一种实现类似功能的替代方法。
我的做法有点不同。首先,我更改了所有未选中复选框的值。到“0”,然后全部选中,因此该值将被提交。
函数checkboxvalues () { $ (" # checkbox-container输入:复选框"). each函数({ if ($ () .prop(“检查”)! = true) { (美元).val(“0”); (美元)。道具(“检查”,真正的); } }); }
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});