我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我的做法有点不同。首先,我更改了所有未选中复选框的值。到“0”,然后全部选中,因此该值将被提交。
函数checkboxvalues () { $ (" # checkbox-container输入:复选框"). each函数({ if ($ () .prop(“检查”)! = true) { (美元).val(“0”); (美元)。道具(“检查”,真正的); } }); }
其他回答
直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });
Ajax动作的例子是(':checked')使用jQuery而不是.val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
参数将得到TRUE或FALSE的值。
@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>
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
如果省略复选框的名称,则不会通过。 只有test_checkbox数组。