简体   繁体   中英

Hide option in select based on other select value

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM