我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我的做法有点不同。首先,我更改了所有未选中复选框的值。到“0”,然后全部选中,因此该值将被提交。
函数checkboxvalues () { $ (" # checkbox-container输入:复选框"). each函数({ if ($ () .prop(“检查”)! = true) { (美元).val(“0”); (美元)。道具(“检查”,真正的); } }); }
其他回答
“我有一大堆默认选中的复选框”——这就是我解决问题的方法:
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>
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
因此,对于这个问题,这个解决方案是多余的,但当我在一个表的不同行中多次出现相同的复选框时,它帮助了我。我需要知道复选框代表的行,也知道复选框的状态(选中/未选中)。
我所做的是将name属性从复选框输入中删除,将它们全部赋予相同的类,并创建一个隐藏输入,该输入将保存与数据等效的JSON。
HTML
<表id = "权限表" > < tr > < td > <input type="checkbox" class="has-permission-cb" value="Jim"> <input type="checkbox" class="has-permission-cb" value="Bob"> <input type="checkbox" class="has-permission-cb" value="Suzy"> < / td > < / tr > 表> < / <input type="hidden" id="has-permissions-values" name="has-permissions-values" value=""> .
Javascript在表单提交上运行
var perms = {}; $ (" .has-permission-checkbox .each(功能)”(){ var userName = this.value; var val = ($(this).prop("checked")) ?1:0 perms[userName] = {"hasPermission": val}; }); $ (" # has-permissions-values ") (.val JSON.stringify perms));
json字符串将作为$_POST["has-permissions-values"]与表单一起传递。在PHP中,将字符串解码为一个数组,您将得到一个关联数组,其中包含每行和每个对应复选框的true/false值。然后很容易遍历并与当前数据库值进行比较。
jQuery版本的@vishnu的答案。
if($('#testName').is(":checked")){
$('#testNameHidden').prop('disabled', true);
}
如果您正在使用jQuery 1.5或以下版本,请使用.attr()函数而不是.prop()