我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
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
)
其他回答
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。
有一个更好的解决办法。 首先,只向选中的复选框提供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);
});
优势: 不需要创建额外的隐藏框,并操作它们。
复选框的问题是,如果它们没有被选中,那么它们就不会随表单一起发布。如果你选中一个复选框并提交一个表单,你将在$_POST变量中获得该复选框的值,你可以使用它来处理表单,如果它未选中,则不会向$_POST变量中添加任何值。
在PHP中,通常可以通过对复选框元素执行isset()检查来解决这个问题。如果你期望的元素没有在$_POST变量中设置,那么我们知道复选框没有被选中,值可以为false。
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
但是如果你创建了一个动态表单,那么你并不总是知道你的复选框的name属性,如果你不知道复选框的名称,那么你就不能使用isset函数来检查它是否与$_POST变量一起发送。
所有答案都很好,但如果您在一个表单中有多个具有相同名称的复选框,并且您希望发布每个复选框的状态。然后我已经解决了这个问题,通过放置一个隐藏字段的复选框(名称相关的我想要的)。
<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />
然后用jquery代码控制复选框的变化状态:
$(documen).on("change", "input[type='checkbox']", function() {
var checkbox_val = ( this.checked ) ? 1 : 0;
$(this).siblings('input.checkbox_handler').val(checkbox_val);
});
现在改变任何复选框,它将改变相关隐藏字段的值。在服务器上,你只能看到隐藏字段,而不是复选框。
希望这能帮助到有这种问题的人。快乐:)