Keyan Rhm Keyan Rhm - 2 months ago 5x
Javascript Question

How to select values in a multiselector based on the selected values of another multiselector

I have two multiselectors as follows, the first one using the Chosen plugin:

<%= select_tag :provinces, options_for_select(, {:multiple => true, class: 'chosen-select chzn-select', :data => {:placeholder => 'Filter Provinces/States'}, :style => "width: 100%; height: 100px;"}%>

<%= :province_ids,
{ include_blank: true },
{multiple: true, data: {placeholder: 'Filter Provinces/States'} }

I want to make the selected values in the
selector, the same as the selected value of the
selector, on page load. Something similar to this:

$(document).ready(function() {
$("#education_plan_province_ids option:selected").each(function () {
$("#provinces option[value='"this"']").prop('selected', true);

Except, of course, that doesn't work :D


var updateDropdown = function() {
  $("#provinces option:selected").removeAttr("selected");
  var educationPlanProvinceIds = $("#education_plan_province_ids").val()
  if (educationPlanProvinceIds) {
    educationPlanProvinceIds.forEach(function(id) {
      $('#provinces option[value="' + id + '"]').prop("selected", true)
  // chosen needs to know when its underlying select element has been changed

$(document).ready(function() {
<script src=""></script>
<select id="education_plan_province_ids" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3" selected="true">3</option>
<select id="provinces" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>