我有一个表单,根据用户提供的数字动态添加输入。该表单用于预订课程,用户选择与会者人数,表格添加输入以阅读他们的详细信息。
只需将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的了解有限。有什么想法吗?
答案 0 :(得分: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) {
...
}
请参阅How to define an array of form fields 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.");
}
?>