Keyan Rhm Keyan Rhm - 4 months ago 6
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(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)), {:multiple => true, class: 'chosen-select chzn-select', :data => {:placeholder => 'Filter Provinces/States'}, :style => "width: 100%; height: 100px;"}%>

<%= f.select :province_ids,
(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{ include_blank: true },
{multiple: true, data: {placeholder: 'Filter Provinces/States'} }
%>


I want to make the selected values in the
:provinces
selector, the same as the selected value of the
:province_ids
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

Answer

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
  $("#provinces").trigger("chosen:updated")
}

$(document).ready(function() {
  updateDropdown()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></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>
<select id="provinces" multiple>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Comments