我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。

是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?


当前回答

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
)

其他回答

我知道这个问题已经提出3年了,但我找到了一个我认为非常有效的解决方案。

您可以检查$_POST变量是否已赋值,并将其保存在变量中。

$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';

isset()函数检查$_POST变量是否被赋值。按照逻辑,如果它没有被分配,那么复选框就不会被选中。

直接复制 美元(文档)。On ('change', "input[type=checkbox]", function () { var checkboxVal = (this.checked) ?1: 0; if (checkboxVal== 1) { (美元)。道具(“检查”,真正的); (美元).val(“true”); } 其他{ (美元)。道具(“检查”,假); (美元).val(“false”); } });

您还可以截取表单。提交事件和提交前的反向检查

$('form').submit(function(event){
    $('input[type=checkbox]').prop('checked', function(index, value){
        return !value;
    });
});

简单的答案。如果你的代码中有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"];