如何获取未选中和已选中复选框的值

时间:2021-12-20 08:28:55

I have a list of checkboxes and want to return their values on submit. I can do this easily for the checked ones, but not for the unchecked? Here's my code so far:

我有一个复选框列表,并希望在提交时返回它们的值。我可以很容易地为已检查的那个做这个,但不是为了未经检查?到目前为止,这是我的代码:

Code to get all address books and existing user address books and output as checkboxes:

代码以获取所有通讯簿和现有用户地址簿并输出为复选框:

foreach ($ch2_response as $ab) {
    if ($ab['visibility'] == "Public") { 
        if (in_array($ab['name'], $userBooks)) { ?>
            <div class="checkbox">
                <label>
                    <input type="checkbox" checked="checked" name="addressBooks[]" value="<?php echo $ab['id']; ?>"><?php echo $ab['name']; ?>
                </label>
            </div>
     <?php   } else { ?>
             <div class="checkbox">
                <label>
                    <input type="checkbox" name="addressBooks[]" value="<?php echo $ab['id']; ?>"><?php echo $ab['name']; ?>
                </label>
            </div>
      <?php  }
    }
}

`
Code to check user's new choices:

`检查用户新选择的代码:

<?php
if (isset($_POST['submit'])) {
    address_books();
}
function address_books() {
    $book = $_POST['addressBooks'];
    if (!isset($book)) {
        $N = count($book);

        echo("You did not select $N book(s): ");
        for ($i = 0; $i < $N; $i++) {
            echo($book[$i] . " ");
        }
    } else {
        $N = count($book);

        echo("You selected $N book(s): ");
        for ($i = 0; $i < $N; $i++) {
            echo($book[$i] . " ");
        }
    }
}

1 个解决方案

#1


0  

You cannot get the values of unchecked checkboxes. The browser won't submit them.

您无法获取未选中复选框的值。浏览器不会提交它们。

You can add a hidden input field with the same name right before each checkbox and give it the false value that you want.

您可以在每个复选框之前添加一个具有相同名称的隐藏输入字段,并为其指定所需的false值。

<input type="hidden" name="addressBooks" value="0">
<input type="checkbox" name="addressBooks" value="1">

When the checkbox is unchecked the browser submit the hidden value to the server

取消选中该复选框后,浏览器会将隐藏值提交给服务器

#1


0  

You cannot get the values of unchecked checkboxes. The browser won't submit them.

您无法获取未选中复选框的值。浏览器不会提交它们。

You can add a hidden input field with the same name right before each checkbox and give it the false value that you want.

您可以在每个复选框之前添加一个具有相同名称的隐藏输入字段,并为其指定所需的false值。

<input type="hidden" name="addressBooks" value="0">
<input type="checkbox" name="addressBooks" value="1">

When the checkbox is unchecked the browser submit the hidden value to the server

取消选中该复选框后,浏览器会将隐藏值提交给服务器