我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。
是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?
当前回答
<input type="checkbox" id="checkbox" name="field_name" value="1">
你可以在服务器端完成,不需要使用隐藏字段, 使用三元运算符:
isset($_POST['field_name']) ? $entity->attribute = $_POST['field_name'] : $entity->attribute = 0;
使用普通IF运算符:
if (isset($_POST['field_name'])) {
$entity->attribute = $_POST['field_name'];
} else {
$entity->attribute = 0;
}
其他回答
到目前为止,我最喜欢的解决方案是放置一个与可能不被选中的复选框同名的隐藏输入。我认为它的工作原理是,如果复选框没有被选中,隐藏输入仍然是成功的,并发送到服务器,但如果复选框被选中,它将覆盖之前的隐藏输入。这样,您就不必跟踪已发布数据中的哪些值应该来自复选框。
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
对于复选框,一个不使用隐藏类型值的简单方法是:
< >形式 <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"];
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 () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
我实际上会这样做。
有我的隐藏输入字段与复选框输入相同的名称
<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;
}
我从一个帖子中得到了这个,从数组中删除重复值