我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
我实际上会这样做。
有我的隐藏输入字段与复选框输入相同的名称
<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />
然后当我post时,我首先删除在$_POST数组中拾取的重复值,然后显示每个唯一的值。
$posted = array_unique($_POST['checkbox_name']);
foreach($posted as $value){
print $value;
}
我从一个帖子中得到了这个,从数组中删除重复值
其他回答
你可以在表单的提交事件中执行一些Javascript。这就是你所能做的,没有办法让浏览器自己做这件事。这也意味着没有Javascript的用户将无法使用表单。 更好的方法是在服务器上知道有哪些复选框,这样就可以推断出那些从提交的表单值(PHP中的$_POST)中缺少的复选框是未选中的。
我使用这个jQuery块,它将在提交时为每个未选中的复选框添加一个隐藏输入。它将保证您每次都为每个复选框提交一个值,而不会弄乱您的标记,并冒着忘记在稍后添加的复选框上执行此操作的风险。它也与您正在使用的任何后端堆栈(PHP、Ruby等)无关。
// Add an event listener on #form's submit action...
$("#form").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "0"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
最简单的解决方案是一个“虚拟”复选框加上隐藏输入,如果你正在使用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。此外,复选框可以在提交前点击多次,仍然可以正常工作。
简单的答案。如果你的代码中有checked="checked"将其改为unchecked="unchecked"
所以你的文本应该是这样的:
输入类型=“复选框” 名称=“您选择的名称” 未选中=“未选中”
如果它不包含这个,你总是可以添加它
对于复选框,一个不使用隐藏类型值的简单方法是:
< >形式 <input type='checkbox' name='self - destruct' value='1'> > < /形式
在PHP中,对于表单数据的发布:
// Sanitize form POST data
$post = filter_var_array($_POST, FILTER_SANITIZE_STRING);
// set the default checkbox value
$selfDestruct = '0';
if(isset($post["selfdestruct"]))
$selfDestruct = $post["selfdestruct"];