首页 > 解决方案 > 如何确保一个下拉菜单始终具有“”值

问题描述

我有 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>

我听菜单有困难。我已经看到了一些附加到选项的代码,但这不是我想要的。

标签: javascripthtmlforms

解决方案


您可以使用以下代码行来实现此目的:

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>


推荐阅读