我有一个表单,当用户在选择下拉列表中选择特定选项时,应该显示一个新字段以输入另一条信息。
基本上,这是常见的“您从哪里听说我们的?”当用户选择other
时,会显示一个新的空字段,以便用户可以输入源(如果源不在列表中)。
但是我真的不知道该怎么做。我一直在使用 PHP 和 HTML 来制作表单并验证它。
要添加一些代码,这是我创建选择的位置
<label for="where_heard">Where heard:</label>
<select name="where_heard"> <?php echo $sources; ?>
</select>
这是我获取源列表的地方:
$query = "SELECT source FROM where_heard";
$stmt = $db->prepare($query);
$stmt->execute();
$sources = "";
while ($row = $stmt->fetch()) {
$sources .= '<option value= "'.$row['source'].'">'.$row['source'].'</option>';
}
最佳答案
你可以使用 jquery 来做到这一点,例如:
$( document ).ready(function() {
$('select').on("change",function(){
if($(this).val() == "other")
$(".other").html("Other: <input type='text' name='other'/>");
else
$(".other").html("");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="where_heard">Where heard:</label>
<select name="where_heard"><option></option><option value="other">Other</option>
</select>
<div class="other"></div>
关于php - 如果选择了确定的选项,如何启用字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32518746/