[英]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. 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我只是想防止用户使用 JavaScript 或任何其他解决方案在两个 select 字段中选择同一个城市
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);
};
References:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.