Keyan Rhm Keyan Rhm - 4 months ago 9
Javascript Question

Append a selected option to a selector

I have two selectors in ERB. They use 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'}}
%>
<%= f.select :province_ids,
(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),
{ include_blank: true },
{multiple: true, data: {placeholder: 'Filter Provinces/States'} }
%>


I am trying to copy the options from one of the selectors to the other one, while keeping the selected options still selected, however it is not working. Here is the Javascript function I have tried:

var selectedVals = [];

$(".chzn-select").chosen().change(function() {
$("#provinces option:selected").each(function () {
console.log ("this value is " + ($(this).val()));
selectedVals.push($(this).val());
});
$("#education_plan_province_ids").empty();
for (var i = 0; i < selectedVals.length; i++) {
console.log (selectedVals[i] + " selected");
$("#education_plan_province_ids").append($("<option>" + selectedVals[i] + "</option>").attr('selected', true));
}
selectedVals = [];
});


Is there another alternative to
attr('selected', true)
?

Answer

Here you go:

$(".chzn-select").chosen().change(function() { 
    $("#education_plan_province_ids").empty(); 
    $("#provinces option:selected").each(function () {
         $("#education_plan_province_ids").append($("<option>" + this.value + "</option>").prop('selected', true)); 
    });
});

I am using prop here and getting rid of extra array (which I think is not needed but you can use it if you want). Also you had parenthesis in wrong place for option.