Hide option in select based on other select value

北城以北 提交于 2019-12-23 04:25:03

问题


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>

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


回答1:


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 demo.

References:

  • document.getElementsByName().
  • document.getElementsByTagName().


来源:https://stackoverflow.com/questions/15101286/hide-option-in-select-based-on-other-select-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!