javascript - 如何确保一个下拉菜单始终具有“”值
问题描述
我有 2 个下拉菜单。但是,我试图确保如果用户从水果菜单中选择水果,那么蔬菜菜单是---
. 如果用户从蔬菜菜单中选择蔬菜,则水果菜单为---
。所以无论如何,至少有一个下拉是---
.
function event_handler() {
var Lists = document.getElementByName('fruit')[0];
Lists.addEventListener('change', reset_menu, false);
}
function reset_menu() {
alert('test');
}
window.onload = event_handler;
<select name="fruit">
<option value="" selected="selected">---</option>
<option value="mango">Mango</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</select>
<select name="veg">
<option value="" selected="selected">---</option>
<option value="carrot">Carrot</option>
<option value="lettuce">Lettuce</option>
<option value="cabbage">Cabbage</option>
</select>
我听菜单有困难。我已经看到了一些附加到选项的代码,但这不是我想要的。
解决方案
您可以使用以下代码行来实现此目的:
list.value = list.options[0].value;
list
这会将下拉/选择列表设置为即 ( ---
)的最大值。因此,当您更改水果列表时,您可以设置list
为您的veg
列表,以便它更改该下拉列表。
现在,当您调用您的reset_menu
函数时,您可以传递您希望重置的列表的列表名称。您的事件处理程序对此进行管理,因此您可以定义在其中传递的列表名称。
请参阅下面的工作示例(以及代码注释以获取进一步解释):
function page_load() {
var fruitList = document.getElementsByName('fruit')[0];
fruitList.addEventListener('change', function() {reset_menu("veg")}); // when the fruit list is changed call the reset_menu function to reset the "veg" menu
var vegList = document.getElementsByName('veg')[0];
vegList.addEventListener('change', function() {reset_menu("fruit")}); // when the vegetable list is changed call the reset_menu function to reset the "veg" menu
}
function reset_menu(listName) {
var list = document.getElementsByName(listName)[0]; // reset the dropdown list with the name passed through
list.value = list.options[0].value;
}
window.onload = page_load;
<select name="fruit">
<option value="" selected="selected">---</option>
<option value="mango">Mango</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
</select>
<select name="veg">
<option value="" selected="selected">---</option>
<option value="carrot">Carrot</option>
<option value="lettuce">Lettuce</option>
<option value="cabbage">Cabbage</option>
</select>
推荐阅读
- css - 当字段是原始的时,如何不触发 ng-pattern?
- c# - 用于打字游戏的波生成器和波数
- php - php count 返回 1 而不是真正的数组长度
- fiddler - Fiddler 代理不适用于 https 请求
- .net - 使用 Jenkins 将点网项目部署到 AWS Lambda
- ios - 音频输出 callkit ActionSheet - 可以从代码开始吗?
- c# - 从 C# 调用时,工作的 powershell 函数无法完成他的工作
- python - 在 msgpack 0.6 中获取字节偏移量
- jsf - 在没有 JavaScript 的情况下动态设置数据列表中的 ID
- sql - 是否可以从 Access 到 QuickBooks 逐行发送信息?