我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单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"];
其他回答
“我有一大堆默认选中的复选框”——这就是我解决问题的方法:
if(($C1)OR($C2)OR... ($C18)){echo "some are checked!";} else{$C1='set';$C2='set';$C3='set';$C4='set';$C5='set';$C6='set';$C7='set';$C8='set';$C9='set';$C10='set';$C11='set';$C12='set';$C13='set';$C14='set';$C15='set';$C16='set';$C17='set';$C18='set';} //(if all are unchecked - set them to 'check' since its your default) the above line will execute the echo if some are unchecked but the checked ones will still have the value parameter set therefore, to keep them set, when writing them in the form, use if($C1){echo "checked";} use the values in the further logic...
! !这种方法的局限性:你不能取消选中所有的东西——它们都会被重新选中
可能看起来很傻,但对我很管用。主要缺点是在视觉上是一个单选按钮,而不是一个复选框,但它不需要任何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;}
小提琴在这里
我想听到你在这段代码中发现的任何问题,因为我在生产中使用它
到目前为止,我最喜欢的解决方案是放置一个与可能不被选中的复选框同名的隐藏输入。我认为它的工作原理是,如果复选框没有被选中,隐藏输入仍然是成功的,并发送到服务器,但如果复选框被选中,它将覆盖之前的隐藏输入。这样,您就不必跟踪已发布数据中的哪些值应该来自复选框。
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。
如果你想提交一个复选框值的数组(包括未选中的项),那么你可以尝试这样做:
<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>
$('form').submit(function(){
$('input[type="checkbox"]:checked').prev().val(1);
});