Reputation:
I see that answer
Set dropdown value based on what is selected in another dropdown using Javascript
And I want make the other hand too. When select an element on select id=b reset the select on id=a, example
select "another option 1" and the id=a set to "---"
why is not working?
HTML:
<select id="a" onchange="changedrop();">
<option value="1">---</option>
<option value="2">option 1</option>
<option value="3">option 2</option>
<option value="4">option 3</option>
</select>
<select id="b" onchange="changedrop();">>
<option value="1">---</option>
<option value="2">another option 1</option>
<option value="3">another option 2</option>
</select>
JS:
function changedrop() {
if (document.getElementById('a').value == '1')
document.getElementById("b").value = '1';
else if (document.getElementById('a').value == '2')
document.getElementById("b").value = '1';
else if (document.getElementById('a').value == '3')
document.getElementById("b").value = '1';
else if (document.getElementById('a').value == '4')
document.getElementById("b").value = '1';
else if (document.getElementById('b').value == '1')
document.getElementById("a").value = '1';
else if (document.getElementById('b').value == '2')
document.getElementById("a").value = '1';
else if (document.getElementById('b').value == '3')
document.getElementById("a").value = '1';
};
Upvotes: 0
Views: 226
Reputation: 3492
The problem is that you need to listen to the onchange
event on both select
elements.
function changeDropA() {
var a = document.getElementById('a');
var b = document.getElementById("b");
if (a.value == '1')
b.value = '1';
else if (a.value == '2')
b.value = '1';
else if (a.value == '3')
b.value = '1';
else if (a.value == '4')
b.value = '1';
};
function changeDropB() {
var a = document.getElementById('a');
var b = document.getElementById("b");
if (b.value == '1')
a.value = '1';
else if (b.value == '2')
a.value = '1';
else if (b.value == '3')
a.value = '1';
}
document.getElementById('a').addEventListener('change', changeDropA);
document.getElementById('b').addEventListener('change', changeDropB);
<select id="a">
<option value="1">---</option>
<option value="2">option 1</option>
<option value="3">option 2</option>
<option value="4">option 3</option>
</select>
<select id="b">
<option value="1">---</option>
<option value="2">another option 1</option>
<option value="3">another option 2</option>
</select>
Upvotes: 1