我想弄清楚的是如何拥有一个 htmlinput当值为other从下拉菜单中选择。现在,下拉列表的值来自 MySQL DB 查询的结果,该查询有效,但我似乎无法弄清楚当我选择其他选项时如何显示输入。
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
使用 javascript,如下面的示例所示。我们可以添加一个input https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input字段并默认隐藏它,使用style属性:<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
有 3rd 方库,例如jQuery http://api.jquery.com/、AngularJS、PrototypeJS 等,它们可以通过添加 DOM 操作的快捷方法来使代码更简单(尽管你应该阅读这个帖子 https://blog.garstasio.com/you-dont-need-jquery/why-not/)。例如,对于 jQuery,使用.on() http://api.jquery.com/on/(对于事件处理程序绑定),.show() http://api.jquery.com/show/ and .hide() http://api.jquery.com/hide/用于输入显示切换等:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)