Reputation: 6212
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
Upvotes: 1
Views: 4225
Reputation: 253308
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:
Upvotes: 2