php - 如何将一组选中/未选中的复选框值传递给 PHP 电子邮件生成器?

标签 php arrays forms checkbox

我在表单中添加了一个复选框,用户可以向其中动态添加行。可以看到表格 here .

我使用数组将每一行的值传递给 PHP 电子邮件生成器,并且对于其他输入都可以正常工作,但我无法使复选框起作用。复选框输入当前看起来像这样:

<input type="checkbox" name="mailing[]" value="Yes">

然后在 PHP 中我有这个:

$mailing = trim(stripslashes($_POST['mailing'][$i]));

但它没有按预期工作,即我只看到选中的第一个复选框为"is",而选中的后续复选框则没有。

另一个问题是我希望为未选中的复选框生成值“否”。

有人可以帮忙吗?

谢谢,

尼克

表格:

<form method="post" action="bookingenginetest.php">
            <p>
                <input type="checkbox" name="mailing[]" value="Yes">
                <label>Full Name:</label> <input type="text" name="name[]">
                <label>Email:</label> <input type="text" name="email[]">
                <label>Telephone:</label> <input type="text" name="telephone[]">
                <span class="remove">Remove</span>
            </p>
            <p>
                <span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
            </p>

        </form>

克隆脚本:

$(document).ready(function() {

                $(".add").click(function() {
                    var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
                    x.find('input').each(function() { this.value = ''; });
                    return false;
                });

                $(".remove").click(function() {
                    $(this).parent().remove();
                });

            });

最佳答案

$mailing = array();
foreach($_POST as $v){
    $mailing[] = trim(stripslashes($v));
}

要处理未选中的复选框,最好为每个复选框设置一个唯一的值:

<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">

<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">

然后有一个复选框列表:

$boxes = array(1,2,3);
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
foreach($boxes as $v){
    if(array_key_exists($v,$p)){
        $mailing[$v] = trim(stripslashes($p[$v]));
    }else{
        $mailing[$v] = 'No';
    }
}

print_r($mailing);

您也可以将其与多个复选框一起使用:

$boxes = 3;
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
for($v = 0; $v < $boxes; $v++){
    if(array_key_exists($v,$p)){
        $mailing[$v] = trim(stripslashes($p[$v]));
    }else{
        $mailing[$v] = 'No';
    }
}

print_r($mailing);

关于php - 如何将一组选中/未选中的复选框值传递给 PHP 电子邮件生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6376112/

相关文章:

php - 使用 jquery 验证插件检查数据库中是否存在电子邮件

php - MYSQL - 不插入数据库?

vb.net - 在 VB 2008 中查找表单的实例

Windows 本地主机上的 PhpStorm 和 xdebug 探查器设置

php - .NET 还是 PHP,企业还是开源?

java - 尝试创建一个自动创建数组并用字节值填充它的程序

ios - Swift 3 从数组中删除不存在于另一个数组中的对象并保持顺序

arrays - 迭代数组中的元素,除了前两个之外,还使用 ​​ "each_slice"

javascript - jquery 删除不删除

php - 比较 MySQL 和 PHP 之间的数据类型