简体   繁体   English

使用php时,将切换按钮的值存储为1,否则将其关闭0,将其存储在同一数组变量中

[英]store the value of toggle button as 1 when it is on else 0 off in same array variable using php

I have a toggle button like this inside a table where the button will be created dynamically based on number of rows fetched from the database 我在表中有一个类似的切换按钮,该按钮将根据从数据库中获取的行数动态创建

<td colspan="3"><input type="checkbox" class="toggleone" name="attendance[]" id="attendance[]" data-toggle="toggle" data-on="Yes" data-off="No"></td>

my problem is the values are not correctly posted when clicking on post button But the count of on buttons is correct but not stored correctly in their position 我的问题是,单击“发布”按钮时值未正确发布,但是“打开”按钮的数量正确,但未正确存储在其位置

button             obtained output               desired output
on                    1                             1
off                   1                             0
off                   0                             0
off                   0                             0
on                    0                             1

Someone help me where i am going wrong. 有人帮助我我要去哪里错了。 Here is my for loop 这是我的循环

for($i=0;$i<($_SESSION['num1']);$i++)
{

        $subcheck = (isset($_POST['attendance'][$i]))? 1 : 0;
        echo $subcheck;
}

Your logic is wrong, $_POST['attendance'][$i] is not what you think it is. 您的逻辑是错误的, $_POST['attendance'][$i]不是您想的那样。 If 2 inputs are checked, the first 2 values of $_POST['attendance'] will be set (indices 0 and 1), regardless of whether they are the first 2 checkboxes or for example the last 2. 如果选中了2个输入,则将设置$_POST['attendance']的前2个值(索引0和1),无论它们是前2个复选框还是后2个复选框。

As you don't set a key nor a value for your checkboxes, you will not be able to identify them on the server. 由于您没有为复选框设置键或值,因此将无法在服务器上识别它们。

To avoid this, you should set the key manually when you build the form or give them a value. 为避免这种情况,在构建表单或为其指定值时应手动设置密钥。

To set the key in a loop, you can use something like: 要将密钥设置为循环,可以使用类似以下内容的代码:

<input type="checkbox" class="toggleone" name="attendance[<?php echo $i; ?>]" id="attendance_<?php echo $i; ?>" data-toggle="toggle" data-on="Yes" data-off="No">

Note that I am not sure if you can use the array notation for the ID (I don't think so...) so I have set the ID using a string. 请注意,我不确定是否可以为ID使用数组符号(我认为不是。。。)所以我已经使用字符串设置了ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM