I was wondering how to synchronize the values and text of two elements. For instance,
<select id="box1" onchange="sync();">
<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>
and then sync(); would look something like….
function sync()
{
box2.selected = box1.selected;
}
Any idea how I would do this?
Thanks,
Matthew
One possible approach:
JS Fiddle demo.
Or, revised and updated somewhat:
JS Fiddle demo.
Note that this approach does assume – and requires – that the
<option>elements are in the same order.To update the original approach, where the order is irrelevant, using ES6 approaches (and the same
data-syncwithcustom attribute approach):JS Fiddle demo.
If you look at the HTML in the Snippet you’ll see that I switched the positions of
<option>elements in the second<select>element to demonstrate that the<option>position doesn’t matter in this latter approach.References:
Array.from().Array.prototype.forEach().document.getElementById().EventTarget.addEventListener().forloop.HTMLElement.dataset.HTMLSelectElement.letstatement.var.