我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。

是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?


当前回答

“我采用了服务器方法。似乎工作得很好-谢谢。- reach4lasasers 12月1日'09 at 15:19“我想从所有者那里推荐它。引用:javascript解决方案取决于服务器处理程序(我没有检查它)

if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";

其他回答

我用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(设置)。

简单的答案。如果你的代码中有checked="checked"将其改为unchecked="unchecked"

所以你的文本应该是这样的:

输入类型=“复选框” 名称=“您选择的名称” 未选中=“未选中”

如果它不包含这个,你总是可以添加它

“我有一大堆默认选中的复选框”——这就是我解决问题的方法:

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...

! !这种方法的局限性:你不能取消选中所有的东西——它们都会被重新选中

我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。

如果你添加以下代码:

<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测试这个。

jQuery版本的@vishnu的答案。

if($('#testName').is(":checked")){
    $('#testNameHidden').prop('disabled', true);
}

如果您正在使用jQuery 1.5或以下版本,请使用.attr()函数而不是.prop()