I got the two following dropdown
lists and I want to remove the option chosen in either one. So if option 1 is chosen, it will not be there in list 2.
<select class='form-dropdown' name='first' id='first'>
<option value='none' selected>No Choice</option>
<option value='Workshop 1'> Workshop 1 </option>
<option value='Workshop 2'> Workshop 2 </option>
<option value='Workshop 3'> Workshop 3 </option>
<option value='Workshop 4'> Workshop 4 </option>
<option value='Workshop 5'> Workshop 5 </option>
</select>
<select class='form-dropdown' name='second' id='second'>
<option value='none' selected>No Choice</option>
<option value='Workshop 1'> Workshop 1 </option>
<option value='Workshop 2'> Workshop 2 </option>
<option value='Workshop 3'> Workshop 3 </option>
<option value='Workshop 4'> Workshop 4 </option>
<option value='Workshop 5'> Workshop 5 </option>
</select>
How is this possible in plain old JavaScript?
EDIT:
The Error Uncaught TypeError: Cannot read property 'addEventListener' of null
was solved by loading the EventListener in window.onload(), see below
window.onload = function () {
document.getElementById("first").addEventListener("change", function() {
show_all("second");
document.querySelector("#second option[value='"+this.value+"']").style.display="none";
});
document.getElementById("second").addEventListener("change", function() {
show_all("first");
document.querySelector("#first option[value='"+this.value+"']").style.display="none";
});
};
function show_all(select_name){
var second_options = document.querySelectorAll("#"+select_name+" option");
for(var i=0;i<second_options.length;i++){
second_options[i].style.display="block";
}
}
You should use
change
event listener on the first dropdown, check the value of it, and remove the element from the second dropdown which has the same value:See demo on JS Bin.
Update
I realized that just using the index wasn't working right since
#second
would diminish in length and it's index would change as well. So I added afor
loop to iterate through#second
and upon a match of values between#first
and#second
options, the index is used to target the matching option and then it's removed.change
event...#first
<option>
selected..remove(index)
targeting#second
Just have a look at this code , working fine for me
HTML CODE :-
Javascript Code :-
I have changed some code in adeneo JSfiddler.
Please check it working on my environment.
Also Find fiddler https://jsfiddle.net/xh3qb8r6/1/
Thanks.
You could add change event to the first
select
then hide the option in second list that have the same value of the current selected, and you could add another function calledshow_all()
to show all the options before hidding the selected one :If you want to avoid the duplicate selection in the both lists you could use :