我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。
如果你添加以下代码:
<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测试这个。
其他回答
简单的答案。如果你的代码中有checked="checked"将其改为unchecked="unchecked"
所以你的文本应该是这样的:
输入类型=“复选框” 名称=“您选择的名称” 未选中=“未选中”
如果它不包含这个,你总是可以添加它
@cpburnz说对了,但是代码太多了,下面是使用更少代码的相同想法:
JS:
// jQuery OnLoad
$(function(){
// Listen to input type checkbox on change event
$("input[type=checkbox]").change(function(){
$(this).parent().find('input[type=hidden]').val((this.checked)?1:0);
});
});
HTML(注意字段名使用数组名):
<div>
<input type="checkbox" checked="checked">
<input type="hidden" name="field_name[34]" value="1"/>
</div>
<div>
<input type="checkbox">
<input type="hidden" name="field_name[35]" value="0"/>
</div>
<div>
对于PHP:
<div>
<input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
<input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>
</div>
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
)
您可以在提交表单之前添加隐藏元素。
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function (i, el) {
if(!el.checked) {
var hidden_el = $(el).clone();
hidden_el[0].checked = true;
hidden_el[0].value = '0';
hidden_el[0].type = 'hidden'
hidden_el.insertAfter($(el));
}
})
});
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。