我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });
其他回答
所有答案都很好,但如果您在一个表单中有多个具有相同名称的复选框,并且您希望发布每个复选框的状态。然后我已经解决了这个问题,通过放置一个隐藏字段的复选框(名称相关的我想要的)。
<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />
然后用jquery代码控制复选框的变化状态:
$(documen).on("change", "input[type='checkbox']", function() {
var checkbox_val = ( this.checked ) ? 1 : 0;
$(this).siblings('input.checkbox_handler').val(checkbox_val);
});
现在改变任何复选框,它将改变相关隐藏字段的值。在服务器上,你只能看到隐藏字段,而不是复选框。
希望这能帮助到有这种问题的人。快乐:)
Ajax动作的例子是(':checked')使用jQuery而不是.val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
参数将得到TRUE或FALSE的值。
最简单的解决方案是一个“虚拟”复选框加上隐藏输入,如果你正在使用jquery:
<input id="id" type="hidden" name="name" value="1/0">
<input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id"
name="dummy-name" value="1/0" checked="checked/blank">
将两个输入的值设置为当前的1/0值,如果为1,则checked=checked。输入字段(活动)现在将始终被发布为1或0。此外,复选框可以在提交前点击多次,仍然可以正常工作。
“我采用了服务器方法。似乎工作得很好-谢谢。- reach4lasasers 12月1日'09 at 15:19“我想从所有者那里推荐它。引用:javascript解决方案取决于服务器处理程序(我没有检查它)
如
if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";
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
)