jQuery show in one list that is selected in another

Scott Baldridge
Scott Baldridge used Ask the Experts™
on
Hello, I have two multi select lists on a page that contain countries.  ListA and ListB  are populated with the countries.

In ListA the user selects only USA and Canada. Now in ListB I want to only show the countries selected in ListA.

How do you do that in jQuery
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Manager / Solutions Architect
Commented:
Something like this?
https://jsfiddle.net/AlexCode/2sLxg29x/

JavaScript
$(document).ready(function() {
  var countries = ['USA', 'Canada', 'Portugal', 'Spain', 'France'],
    $sel1 = $('#sel1'),
    $sel2 = $('#sel2');

  var populateSelect = function($sel, options) {
    var html = '';
    for (var c = 0; c < options.length; c++) {
      html += '<option value="' + options[c] + '">' + options[c] + '</option>';
    }

    $sel.html(html);
  }

  $sel1.on('change', function() {
    $sel2.empty();

    var sel2Options = [];
    $sel1.find(':selected').each(function(i, selected) {
      sel2Options.push($(selected).text());
    });

    populateSelect($sel2, sel2Options);
  });

  populateSelect($sel1, countries);

});

Open in new window

HTML
<select id="sel1" multiple></select>
<select id="sel2" multiple></select>

Open in new window

Author

Commented:
Thank you! That was the nudge I needed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial