php - 如果选择了确定的选项,如何启用字段?

标签 php html

我有一个表单,当用户在选择下拉列表中选择特定选项时,应该显示一个新字段以输入另一条信息。

基本上,这是常见的“您从哪里听说我们的?”当用户选择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/

相关文章:

php - 允许页面仅在 iframe 中加载

python - 是否有与 PHP-FPM 等效的 Python?

javascript - Flot:如何在条形图中设置数字样式?

html - 如何在不影响按钮内容的情况下使按钮呈圆形?

Python使用漂亮的汤从html中提取属性

html - css如何在自动调整宽度时将一个div依赖于另一个div

php - 使用 PHP 的 native SOAP 类时生成 WSDL?

php - 如何在 foreach 循环之前/之后触发代码,仅当在 PHP 7.4+ 中以有效方式输入此循环?

php - 访问已删除用户的信息

javascript - 在 HTML 下拉菜单中显示 PHP 变量