我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
一句话解决方案:
$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;
其他回答
您还可以截取表单。提交事件和提交前的反向检查
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
Ajax动作的例子是(':checked')使用jQuery而不是.val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
参数将得到TRUE或FALSE的值。
我们可以检查$_POST/Request元素是否有它。然后将它赋值给一个变量。
$value = (null !== $_POST['checkboxname']) ?“是”:“不是”;
这与isset()函数非常相似。但是isset()函数不能用于表达式的结果。我们可以用null检查它的结果,并达到相同的效果。
最后的值只是虚数。如果所需字段为布尔类型,我们可以将“YES”更改为1,将“NO”更改为0。
这个解决方案的灵感来自@desw的一个。
如果您的输入名称是“表单样式”的,那么只要选中一个复选框,您就会失去与复选框值的数组索引关联,每次选中一个复选框,这种“分离”就增加一个单元。这可能是用于插入由某些字段组成的雇员的表单的情况,例如:
<input type="text" name="employee[]" />
<input type="hidden" name="isSingle[] value="no" />
<input type="checkbox" name="isSingle[] value="yes" />
如果您一次插入三个员工,并且第一个和第二个员工是单个的,那么您最终将得到一个5元素的isSingle数组,因此您将不能一次遍历三个数组,例如,为了在数据库中插入员工。
你可以用一些简单的数组后处理来克服这个问题。我在服务器端使用PHP,我这样做:
$j = 0;
$areSingles = $_POST['isSingle'];
foreach($areSingles as $isSingle){
if($isSingle=='yes'){
unset($areSingles[$j-1]);
}
$j++;
}
$areSingles = array_values($areSingles);
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
)