How To Synchronize Two Select Elements January 30, 2024 Post a Comment I was wondering how to synchronize the values and text of two elements. For instance, OneSolution 1: One possible approach:functionsync(el1, el2) { // if there is no el1 argument we quit here:if (!el1) { returnfalse; } else { // caching the value of el1:var val = el1.value; // caching a reference to the element with// with which we should be synchronising values:var syncWith = document.getElementById(el2); // caching the <option> elements of that <select>:var options = syncWith.getElementsByTagName('option'); // iterating over those <option> elements:for (var i = 0, len = options.length; i < len; i++) { // if the value of the current <option> is equal// to the value of the changed <select> element's// selected value:if (options[i].value == val) { // we set the current <option> as// as selected: options[i].selected = true; } } } } // caching the <select> element whose change event should// be reacted-to:var selectToSync = document.getElementById('box1'); // binding the onchange event using an anonymous function: selectToSync.onchange = function(){ // calling the function:sync(this,'box2'); }; Copyfunctionsync(el1, el2) { if (!el1) { returnfalse; } 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'); };Copy<selectid="box1"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select><selectid="box2"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select>CopyJS Fiddle demo.Or, revised and updated somewhat:functionsync() { // caching the changed element:let el = this; // retrieving the id of the element we should synchronise with// from the changed-element's data-syncwith custom attribute,// using document.getElementById() to retrieve that that element.document.getElementById( el.dataset.syncwith ) // retrieving the <options of that element// and finding the <option> at the same index// as changed-element's selectedIndex (the index// of the selected <option> amongst the options// collection) and setting that <option> element's// selected property to true: .options[ el.selectedIndex ].selected = true; } // retrieving the element whose changes should be// synchronised with another element:var selectToSync = document.getElementById('box1'); // binding the snyc() function as the change event-handler: selectToSync.addEventListener('change', sync); Copyfunctionsync() { let el = this; document.getElementById(el.dataset.syncwith).options[el.selectedIndex].selected = true; } var selectToSync = document.getElementById('box1'); selectToSync.addEventListener('change', sync);Copy<selectid="box1"data-syncwith="box2"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select><selectid="box2"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select>CopyJS 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-syncwith custom attribute approach):functionsync() { // caching the changed element (since// we're using it twice):let el = this; // retrieving the id of the element to synchronise 'to' from // the 'data-syncwith' custom attribute of the changed element,// and retrieving its <option> elements. Converting that// Array-like collection into an Array using Array.from():Array.from(document.getElementById(el.dataset.syncwith).options) // Iterating over the array of options using// Array.prototype.forEach(), and using an Arrow function to// pass the current <otpion> (as 'opt') setting that current// <option> element's selected property according to Boolean// returned by assessing whether the current option's value// is (exactly) equal to the value of the changed element: .forEach(opt => opt.selected = opt.value === el.value); } var selectToSync = document.getElementById('box1'); selectToSync.addEventListener('change', sync); Copyfunctionsync() { 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);Copy<selectid="box1"data-syncwith="box2"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select><selectid="box2"><optionvalue="1">One</option><optionvalue="3">Three</option><optionvalue="2">Two</option></select>CopyJS 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().Arrow functions.document.getElementById().EventTarget.addEventListener().for loop.HTMLElement.dataset.HTMLSelectElement.let statement.var.Solution 2: In the Actual browsers you dont have to do to much...<selectid="box1"onchange="box2.value=this.value;"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select><selectid="box2"><optionvalue="1">One</option><optionvalue="2">Two</option><optionvalue="3">Three</option></select>CopyJsfiddle DEMOSolution 3: Without jQuery: for (var i=0; i<document.getElementById('box1').options.length; i++) if (document.getElementById('box1').options[i].selected) for (var j=0; j<document.getElementById('box2').options.length; j++) if (document.getElementById('box1').options[i].value == document.getElementById('box2').options[j].value) document.getElementById('box2').options[j].selected = true; CopySolution 4: With jQuery:Note:on method requires jQuery > 1.7jQuery(function($) { $('#first').on('change', function() { var sel = $('option:selected', this).val(); $('#second option').filter(function(index, el) { return el.value == sel; }).prop('selected', true); }); });Copy<selectname="first"id="first"autocomplete="off"><optionvalue="0">-- Select one option --</option><optionvalue="1">First</option><optionvalue="2">Second</option><optionvalue="3">Third</option><optionvalue="4">Fourth</option><optionvalue="5">Fifth</option><optionvalue="6">Sixth</option></select><selectname="second"id="second"autocomplete="off"><optionvalue="0">-- Select one option --</option><optionvalue="1">First</option><optionvalue="2">Second</option><optionvalue="3">Third</option><optionvalue="4">Fourth</option><optionvalue="5">Fifth</option><optionvalue="6">Sixth</option></select><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>Copy Share Post a Comment for "How To Synchronize Two Select Elements" Top Question Activating Onbeforeunload Only When Field Values Have Changed What I'm trying to achieve is to Warn the user of unsav… Onpropertychange For A Textbox In Firefox? How to handle the onpropertychange for a textbox in Firefox… Animate A Div Box With AngularJS How can I animate a div-Box in AngularJS? I've tried se… Jquery UI Add Class With Animation Does't Work See my jsfiddle (apologies for putting the javascript into … AmCharts Pie - How To Get Slice To Pull Out On RollOverSlice? I am having a lot of difficulties navigating through amChar… I Need To Check A JavaScript Array To See If There Are Any Duplicate Values. I have an array var a =['color', 'radius',… How To Eliminate Unused Arguments In An Opacity Fade? element is called but never used, they are just passed back… How Can I Attach Prototype To Object Literals In JS I am trying to understand JavaScripts Prototypal nature and… Add Extra Divs To The Dom Jquery ( Toogle Click More Function) this is my first post in this website and I just wonder if … URIError: Failed To Decode Param '///%PUBLIC_URL%/manifest.json' I am trying to revive an old React app that I coded a year … December 2024 (1) November 2024 (38) October 2024 (65) September 2024 (22) August 2024 (370) July 2024 (342) June 2024 (693) May 2024 (1296) April 2024 (799) March 2024 (1548) February 2024 (1677) January 2024 (1305) December 2023 (1285) November 2023 (366) October 2023 (580) September 2023 (320) August 2023 (332) July 2023 (278) June 2023 (364) May 2023 (203) April 2023 (137) March 2023 (131) February 2023 (189) January 2023 (267) December 2022 (133) November 2022 (231) October 2022 (171) September 2022 (167) August 2022 (488) July 2022 (288) June 2022 (299) Menu Halaman Statis Beranda © 2022 - JavaScript Apprenticeships