1

我有一个表单,可以根据用户提供的数字动态添加输入。该表格用于预订课程,用户选择参加者的数量,表格添加输入以读取他们的详细信息。

只需将 FOR 循环的计数插入相关属性即可生成和命名输入:

var inputEl = $('<input type="text" class="text delegate" name="delegate_name_' + i + '" id="delegate-name-' + i + '" placeholder="Delegate Name ' + (i + 1) + '" /><input type="text" class="text delegate" name="delegate_email_' + i + '" id="delegate-email-' + i + '" placeholder="Delegate Email ' + (i + 1) + '" /><input type="text" class="text delegate" name="delegate_tel_' + i + '" id="delegate-tel-' + i + '" placeholder="Delegate Telephone ' + (i + 1) + '" />')

这一切都很好,花花公子,工作正常。但是,我即将编写用于邮寄表单的 PHP,我想到我不知道如何告诉邮件脚本它需要读取多少输入。

我认为它需要另一个 FOR 循环来运行并创建相关的电子邮件条目,但我对 PHP 的了解有限。有任何想法吗?

4

1 回答 1

2

如果您为动态创建的字段(以及相同类型的预渲染版本)提供一个name属性,delegates[]那么 PHP 会将其存储为内部数组。

<input type="text" name="delegates[]" id="delegate1">
<input type="text" name="delegates[]" id="delegate2">
<input type="text" name="delegates[]" id="delegate3">
<input type="text" name="delegates[]" id="delegate4">

然后应该很容易迭代该数组,执行您需要的操作。

foreach ($_POST['delegates'] as $delegate) {
    ...
}

请参阅如何定义表单字段数组 PHP

特别是对于您发布的代码,我相信您需要执行类似的操作:

<?php
    // Set properties
    $to     = "mail@mail.com";  // Enter the email address to send email to.
    $subject    = "Booking Form Submission";            // Enter a subject for your email.

    // Set the web address to forward the user to when the mail is successfully sent.
    $url        = "success.html";

    $message = $_POST['message'];

    foreach ($_POST['delegates'] as $delegate) {
        $message .= "\r\n$delegate";
    }

    // Send the email, you don't need to change anything below this line.
    $sent = mail($to, $subject, $message, "From: " . $_POST["email"], "-f" . $_POST["email"], "Telephone:" . $_POST["tel"], "Payment Method:". $_POST["payment"], "Payment Address:" . $_POST["address"], "Purchase Order Number:" . $_POST["pono"], "No. of Delegates:" . $_POST["delno"], "Residential?:" . $_POST["residential"], "Exam?:" . $_POST["exam"], "Total Cost:" . $_POST["total_cost"]);

    // See if mail was sent
    if($sent) {
        // Email was sent successfully. Note that all we can see is that the mail was sent
        // from the server, but we cannot determine if it arrived at it's destination.
        header("Location: " . $url);
    } else {
        // Mail was not sent
        die("Your email has not been sent.");
    }
?>
于 2013-11-04T14:18:23.080 回答