<form name="form" action="" method="get">
<input type="text" name="name" id="name" value="My name">
<textarea name="about_me" id="about_me"></textarea>
<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />
<select name="level">
<option value="Beginner">Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Expert">Expert </option>
</select>
</form>
我有这样的形式,
我的表单字段是动态添加的.
提交表单后,我需要识别字段类型,需要知道名称是文本框值,about_me是textarea输入,性别是无线电选项,级别是下拉等.
是在PHP中找出表单字段类型的任何方法.
最佳答案 第一:采取MyWay的方法.这很简单直截了当.但是,如果要构建更复杂的结构,可以使用以下代码.它将隐藏字段设置为数组并保存名称和类型,以::分隔
HTML页面:
<form name="form" action="" method="get">
<input type="hidden" name="fields[]" value="name:text">
<input type="hidden" name="fields[]" value="about_me:textarea">
<input type="hidden" name="fields[]" value="gender:radio">
<input type="hidden" name="fields[]" value="level:select">
<input type="text" name="name" id="name" value="My name">
<textarea name="about_me" id="about_me"></textarea>
<input type="radio" name="gender" value="male" />
<input type="radio" name="gender" value="female" />
<select name="level">
<option value="Beginner">Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Expert">Expert </option>
</select>
</form>
然后,在您的PHP文件中:
$fields = $_POST["fields"];
foreach ($fields as $field) {
list($name, $type) = explode(':', $field);
$val = (!empty($_POST[$name]))?$_POST[$name]:"";
if ($type == "textarea") {
// do sth. useful with it
// the value is in $val (if there's one)
}
}