Categories

向HTML联系人表单添加字段

Gordon J. Blair April 20, 2011
Rating: 4.5/5. From 11 votes.
Please wait...

本教程将向您展示如何 add fields to the HTML contact form. 本教程是本教程的延续 如何在HTML中创建联系人表单. 如果您有该教程中的文件,然后打开继续,否则 download them

Part 1. HTML

Open the index.html file with your prefered HTML editor. 我们有两个输入,一个textarea元素和两个按钮. 所以让我们给它添加更多的功能,比如复选框、单选按钮和下拉列表. The HTML 所有这些元素的语法都很简单,您可以在下面检查一下. 在Submit和Reset按钮之后添加此代码.

Additional options:

	USA
Canada
Mexico

Do you agree?

Yes
No

从下拉菜单中选择一个项目:


让我们澄清一下这段代码中一些有趣的地方. 您可能已经注意到,分配给复选框的名称并没有不同, 就像前面添加的文本字段一样, 最后还有方括号. 括号定义了这是an array variable. So this is how it works. For each checkbox you check, the check[] array 接收按下的复选框的值. 例如,选中美国和加拿大复选框后,您的 check[] array contains the values checked_usa and check_canada as its elements.

单选按钮和下拉菜单没有什么特别的地方. We’ve assigned the same name “cf_radio_button” to both of the radio buttons, 因为你不能同时选择两者, 所以它们不需要有唯一的名字.

下拉列表语法也非常简单. Open the tag tag. The

这是添加了这些代码后你应该得到的结果.

HTML contact form(click to enlarge)

Part 2. PHP

So, 现在我们有了页面上的元素, 我们应该处理他们发送的数据,并添加到发送的电子邮件中. Below, is the final code of contact.php file


	

	

让我们看看这里添加了哪些部分的代码,以及它们实际做了什么.

We’ll use the php function foreach() to iterate through an array 的每一个元素 array into a variable called $value. Then we create a variable $check_boxes 然后用每个元素的值增加它 array

foreach($_POST['check'] as $value) {
	$check_boxes .= $value." ";
}

As you see below, 单选按钮和下拉列表的定义方式与输入文本字段类似. 我们创建一个php变量,并将从单选框或下拉列表发送的数据赋值给它

$radio_button = $_POST['cf_radio_button'];
$drop_down_item = $_POST['cf_drop_down'];

这段代码也类似于我们之前所做的. 我们只是在最后的邮件中添加新的数据

$body_message .= "Additional options checked: ".$check_boxes."\n";
$body_message .= "Did the customer agree: ".$radio_button."\n";
$body_message .= "从下拉列表中选择的项目:".$drop_down_item;

TIP: One small update that might be usefull. In the previous version of the script, after the javascript alert message, there was a manual redirect 到您在代码中指定的页面 window.location = ‘contact_page.html’; So if you rename the contact_page.html 对于其他内容,您需要更正文件名 contact.php 一个更好的方法是用下面的代码替换那个代码

history.back(1);

基本上,代码本身解释了它的作用. This is the same as clicking the Back button in your browser.

This entry was posted in Working with HTML and tagged contact, field, form, HTML, input, php, radio, select. Bookmark the permalink.

Submit a ticket

如果您仍然无法找到关于您的问题的足够的教程,请使用以下链接向我们的技术支持团队提交请求. 我们将在接下来的24小时内为您提供我们的帮助和协助: Submit a ticket