Keyan Rhm Keyan Rhm - 1 year ago 71
Javascript Question

Append a selected option to a selector

I have two selectors in ERB. They use the Chosen plugin:

<%= select_tag :provinces,
{:multiple => true, class: 'chosen-select chzn-select',
:data => {:placeholder => 'Filter Provinces/States'}}
<%= :province_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()));
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 Source

Here you go:

$(".chzn-select").chosen().change(function() { 
    $("#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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download