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

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


当前回答

Ajax动作的例子是(':checked')使用jQuery而不是.val();

            var params = {
                books: $('input#users').is(':checked'),
                news : $('input#news').is(':checked'),
                magazine : $('input#magazine').is(':checked')
            };

参数将得到TRUE或FALSE的值。

其他回答

<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;
}

我更喜欢整理$_POST

if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;

它介意,如果POST没有checkboxname值,它是unchecked的,所以,给它赋一个值。

你可以为你的复选框值创建一个数组,并创建一个函数来检查值是否存在,如果不存在,它会介意是否未选中,你可以给值赋值

“我有一大堆默认选中的复选框”——这就是我解决问题的方法:

if(($C1)OR($C2)OR... ($C18)){echo "some are checked!";} else{$C1='set';$C2='set';$C3='set';$C4='set';$C5='set';$C6='set';$C7='set';$C8='set';$C9='set';$C10='set';$C11='set';$C12='set';$C13='set';$C14='set';$C15='set';$C16='set';$C17='set';$C18='set';} //(if all are unchecked - set them to 'check' since its your default) the above line will execute the echo if some are unchecked but the checked ones will still have the value parameter set therefore, to keep them set, when writing them in the form, use if($C1){echo "checked";} use the values in the further logic...

! !这种方法的局限性:你不能取消选中所有的东西——它们都会被重新选中

一句话解决方案:

$option1ChkBox = array_key_exists('chkBoxName', $_POST) ? true : false;

这里的大多数答案都需要使用JavaScript或重复的输入控件。有时这需要完全在服务器端处理。

我相信解决这个常见问题的关键是表单的提交输入控件。

要成功地解释和处理复选框的未选中值,您需要具备以下知识:

复选框的名称 表单提交输入元素的名称

通过检查表单是否已提交(将一个值分配给提交输入元素),可以假定任何未选中的复选框值。

例如:

<形式 <输入=“value1”类型=“checkbox”值=“1”> checkbox One<br/> <输入=“value2”类型=“checkbox”=“价值”1“checked=“checked=”>“checked”> 2 <br/> <输入=“value3”类型=“checkbox”值=“1”> checkbox Three<br/> <输入=“submit”类型=“submit”值=“submit”> < / form >

在使用PHP时,检测选中了哪些复选框是相当简单的。

<?php

$checkboxNames = array('value1', 'value2', 'value3');

// Persisted (previous) checkbox state may be loaded 
// from storage, such as the user's session or a database.
$checkboxesThatAreChecked = array(); 

// Only process if the form was actually submitted.
// This provides an opportunity to update the user's 
// session data, or to persist the new state of the data.

if (!empty($_POST['submit'])) {
    foreach ($checkboxNames as $checkboxName) {
        if (!empty($_POST[$checkboxName])) {
            $checkboxesThatAreChecked[] = $checkboxName;
        }
    }
    // The new state of the checkboxes can be persisted 
    // in session or database by inspecting the values 
    // in $checkboxesThatAreChecked.
    print_r($checkboxesThatAreChecked);
}

?>

初始数据可以在每个页面加载时加载,但只有在提交表单时才应该修改。由于预先知道复选框的名称,因此可以逐个遍历和检查它们,因此它们的单独值的缺失表明它们没有被选中。