One possible approach:
function sync(el1, el2) {
function sync(el1, el2) { if (!el1) { return false; } else { var val = el1.value; var syncWith = document.getElementById(el2); var options = syncWith.getElementsByTagName('option'); for (var i = 0, len = options.length; i < len; i++) { if (options[i].value == val) { options[i].selected = true; } } } } var selectToSync = document.getElementById('box1'); selectToSync.onchange = function() { sync(this, 'box2'); };
<select id="box1"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <select id="box2"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select>
JS Fiddle demo .
Or, somewhat revised and updated:
function sync() {
function sync() { let el = this; document.getElementById(el.dataset.syncwith).options[el.selectedIndex].selected = true; } var selectToSync = document.getElementById('box1'); selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <select id="box2"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select>
JS Fiddle demo .
Note that this approach assumes - and requires - that the <option> elements are in the same order.
To update the original approach when the order doesn't matter, use the ES6 approaches (the same data-syncwith ):
function sync() {
function sync() { let el = this; Array.from(document.getElementById(el.dataset.syncwith).options).forEach(opt => opt.selected = opt.value === el.value); } let selectToSync = document.getElementById('box1'); selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <select id="box2"> <option value="1">One</option> <option value="3">Three</option> <option value="2">Two</option> </select>
JS Fiddle demo .
If you look at the HTML in the snippet, you will see that I switched the positions of the <option> elements in the second <select> element to demonstrate that the position of the <option> doesn't matter in this last approach.
Literature:
source share