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

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


当前回答

这里的大多数答案都需要使用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);
}

?>

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

其他回答

我们可以检查$_POST/Request元素是否有它。然后将它赋值给一个变量。

$value = (null !== $_POST['checkboxname']) ?“是”:“不是”;

这与isset()函数非常相似。但是isset()函数不能用于表达式的结果。我们可以用null检查它的结果,并达到相同的效果。

最后的值只是虚数。如果所需字段为布尔类型,我们可以将“YES”更改为1,将“NO”更改为0。

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

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

我使用这个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

Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.

由于我在数据库中存储值“Y”和“N”,并通过页面上的选中和未选中复选框表示它们,我为每个值(复选框)添加了“Y”和“N”值的隐藏字段,然后使用复选框进行可视化表示,并使用简单的JavaScript函数check()来根据选择设置if的值。

<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>

使用一个JavaScript onclick监听器和调用函数check()在我的网页上的每个复选框:

function check(me)
{
  if(me.checked)
  {
    me.previousSibling.previousSibling.value='Y';
  }
  else
  {
    me.previousSibling.previousSibling.value='N';
  }
}

这样,“Y”或“N”值总是发送到服务器端脚本,它知道什么是应该更新的字段,没有必要将复选框“上”值转换为“Y”或未接收复选框转换为“N”。

注意:空格或新行也是兄弟姐妹,所以这里我需要。previoussibling . previoussibling .value。如果没有空格,则只有.previousSibling.value


你不需要像以前那样显式地添加onclick监听器,你可以使用jQuery库动态添加点击监听器函数来更改页面中所有复选框的值:

$('input[type=checkbox]').click(function()
{
  if(this.checked)
  {
    $(this).prev().val('Y');
  }
  else
  {
    $(this).prev().val('N');
  }
});

因此,对于这个问题,这个解决方案是多余的,但当我在一个表的不同行中多次出现相同的复选框时,它帮助了我。我需要知道复选框代表的行,也知道复选框的状态(选中/未选中)。

我所做的是将name属性从复选框输入中删除,将它们全部赋予相同的类,并创建一个隐藏输入,该输入将保存与数据等效的JSON。

HTML

<表id = "权限表" > < tr > < td > <input type="checkbox" class="has-permission-cb" value="Jim"> <input type="checkbox" class="has-permission-cb" value="Bob"> <input type="checkbox" class="has-permission-cb" value="Suzy"> < / td > < / tr > 表> < / <input type="hidden" id="has-permissions-values" name="has-permissions-values" value=""> .

Javascript在表单提交上运行

var perms = {}; $ (" .has-permission-checkbox .each(功能)”(){ var userName = this.value; var val = ($(this).prop("checked")) ?1:0 perms[userName] = {"hasPermission": val}; }); $ (" # has-permissions-values ") (.val JSON.stringify perms));

json字符串将作为$_POST["has-permissions-values"]与表单一起传递。在PHP中,将字符串解码为一个数组,您将得到一个关联数组,其中包含每行和每个对应复选框的true/false值。然后很容易遍历并与当前数据库值进行比较。