我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
如果你想提交一个复选框值的数组(包括未选中的项),那么你可以尝试这样做:
<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>
$('form').submit(function(){
$('input[type="checkbox"]:checked').prev().val(1);
});
其他回答
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。
一种常见的方法是在每个复选框中附带一个隐藏变量。
<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>
在服务器端,我们首先检测隐藏变量列表,对于每个隐藏变量,我们尝试查看相应的复选框条目是否提交到表单数据中。
服务器端算法可能是这样的:
for input in form data such that input.name endswith .hidden
checkboxName = input.name.rstrip('.hidden')
if chceckbName is not in form, user has unchecked this checkbox
上面并没有完全回答这个问题,但是提供了一种实现类似功能的替代方法。
这是对之前答案的一种尝试,以自动保留具有特定值(在本例中为0)的未选中复选框,而不会在提交时选中所有复选框。
$("form").submit(function () {
let this_master = $(this);
// Remove any of the hidden values that may already be there (if the user previously canceled the submit)
this_master.find("*[id^='hiddenchkinput_']").remove();
// Get all unchecked checkboxes
this_master.find('input:checkbox:not(:checked)').each(function () {
let thisChk = $(this);
// Create a hidden input with the same name as the checkbox
let newInput = document.createElement('input');
$(newInput).attr('name', thisChk.attr('id'))
.attr('id', 'hiddenchkinput_' + thisChk.attr('id'))
.attr('type', 'hidden')
.val('0');
// Append the new input to the end of the form
this_master.append(newInput);
});
})
@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>
我用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(设置)。