我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
<input type="checkbox" id="checkbox" name="field_name" value="1">
你可以在服务器端完成,不需要使用隐藏字段, 使用三元运算符:
isset($_POST['field_name']) ? $entity->attribute = $_POST['field_name'] : $entity->attribute = 0;
使用普通IF运算符:
if (isset($_POST['field_name'])) {
$entity->attribute = $_POST['field_name'];
} else {
$entity->attribute = 0;
}
其他回答
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
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
)
对于复选框,一个不使用隐藏类型值的简单方法是:
< >形式 <input type='checkbox' name='self - destruct' value='1'> > < /形式
在PHP中,对于表单数据的发布:
// Sanitize form POST data
$post = filter_var_array($_POST, FILTER_SANITIZE_STRING);
// set the default checkbox value
$selfDestruct = '0';
if(isset($post["selfdestruct"]))
$selfDestruct = $post["selfdestruct"];
复选框的问题是,如果它们没有被选中,那么它们就不会随表单一起发布。如果你选中一个复选框并提交一个表单,你将在$_POST变量中获得该复选框的值,你可以使用它来处理表单,如果它未选中,则不会向$_POST变量中添加任何值。
在PHP中,通常可以通过对复选框元素执行isset()检查来解决这个问题。如果你期望的元素没有在$_POST变量中设置,那么我们知道复选框没有被选中,值可以为false。
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
但是如果你创建了一个动态表单,那么你并不总是知道你的复选框的name属性,如果你不知道复选框的名称,那么你就不能使用isset函数来检查它是否与$_POST变量一起发送。
我用JavaScript解决了这个问题:
<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">
注意在这两个输入元素之间不要有任何空格或换行符!
你可以使用this.previousSibling.previousSibling来获取“上层”元素。
使用PHP,您可以检查命名隐藏字段为0(未设置)或1(设置)。