Reputation: 139
my-select
is the main, when is chosen by users, it opens popup (what works right now), but what I
want is that when I choose my-select2
it should change the value
too.
<select id="my-select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="my-select2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
document.getElementById('my-select').addEventListener('change', function() {
console.log('You selected: ', this.value);
});
Upvotes: 0
Views: 2722
Reputation: 264
document.getElementById('my-select').addEventListener('change', function() {
console.log('You selected: ', this.value);
selectOptionInMySelect2(this.value)
});
function selectOptionInMySelect2(value) {
const selectElement = document.getElementById('my-select2');
const allOptions = selectElement.options;
for(let i=0; i < allOptions.length; i++) {
if(allOptions[i].value == value) {
selectElement.selectedIndex = i;
break;
}
}
}
Included the same ids and values as that in your snippet. Working example here
Did not realise that an answer already got posted till the time I was editing this. Wow, community!
Just in case, the option sequence isn't the same in both selects, this will work. Cheers!
Upvotes: 1
Reputation: 581
there is a very simple way to do that.
In the change listener, you just simply call the other select and change it's selected index after applying your own logic.
Please check the code here:
document.getElementById('my-select').addEventListener('change', function() {
console.log('You selected: ', this.value);
document.getElementById("my-select2").selectedIndex = this.selectedIndex;
});
<select id="my-select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="my-select2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Upvotes: 2