我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
对于复选框,一个不使用隐藏类型值的简单方法是:
< >形式 <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
if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;
它介意,如果POST没有checkboxname值,它是unchecked的,所以,给它赋一个值。
你可以为你的复选框值创建一个数组,并创建一个函数来检查值是否存在,如果不存在,它会介意是否未选中,你可以给值赋值
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
我用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(设置)。
我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。
如果你添加以下代码:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
浏览器不会真正关心您在这里做了什么。浏览器将把两个参数都发送给服务器,服务器必须决定如何处理它们。
例如,PHP将最后一个值作为要使用的值(参见:重复HTTP GET查询键的权威位置)
但是我使用过的其他系统(基于Java)是这样做的——它们只提供第一个值。 .NET会给你一个包含这两个元素的数组
我会试着在某个时候用node.js, Python和Perl测试这个。
可能看起来很傻,但对我很管用。主要缺点是在视觉上是一个单选按钮,而不是一个复选框,但它不需要任何javascript。
HTML
Initialy checked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="a" value="1" checked>
<input type="radio" name="a" value="0">
</span>
<br/>
Initialy unchecked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="b" value="1">
<input type="radio" name="b" value="0" checked>
</span>
和CSS
span input
{position: absolute; opacity: 0.99}
span input:checked
{z-index: -10;}
span input[value="0"]
{opacity: 0;}
小提琴在这里
我想听到你在这段代码中发现的任何问题,因为我在生产中使用它