根据其他选择值在选择中隐藏选项 [英] Hide option in select based on other select value

查看:91
本文介绍了根据其他选择值在选择中隐藏选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于拼车网站,我有两个到达城市和离开城市的选择标签,我想防止用户在到达城市的选择中选择相同的城市,这里选择离开城市是一个示例:

I have two select tags of arrival city and departure city for carpool web site, I want to prevent the user from selecting the same city in the select of arrival city and the select of the departure city here is an example :

  <select name="departure" size="1">
    <option value="1">NY</option>
    <option value="2">FL</option>
    <option value="3">LA</option>
  </select>

  <select name="arrival" size="1">
    <option value="1">NY</option>
    <option value="2">FL</option>
    <option value="3">LA</option>
  </select>

我只是想防止用户使用JavaScript或任何其他解决方案在两个选择字段中选择同一城市

I just want to prevent the user from selecting the same city in both select fields using JavaScript or any other solution

推荐答案

对于简单的解决方案,我建议:

For a simple solution, I'd suggest:

function deDupe(el) {
    var opt = el.selectedIndex,
        other = el.name == 'departure' ? document.getElementsByName('arrival')[0] : document.getElementsByName('departure')[0],
        options = other.getElementsByTagName('option');
    for (var i = 0, len = options.length; i < len; i++) {
        options[i].disabled = i == opt ? true : false;
    }
}

var departure = document.getElementsByName('departure')[0],
    arrival = document.getElementsByName('arrival')[0];

deDupe(document.getElementsByName('departure')[0]);

departure.onchange = function () {
    deDupe(departure);
};
arrival.onchange = function () {
    deDupe(arrival);
};

JS Fiddle演示.

参考文献:

这篇关于根据其他选择值在选择中隐藏选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆