Question

I have a Rails 3 application where I allow the user to apply tags to their listing. I've read a few stackoverflow threads with similar questions but this one is unique since I am using a frontend framework. I am using the webarch framework: http://www.revox.io/webarch/form_elements.html

If you CTRL + F "Multi Select" you can see the exact element that I am using.

Summary

I use this code to populate tags:

<%= f.collection_select :tag_ids, Tag.all, :id, :name, {:selected => @listing.tags.map(&:id).map(&:to_i)}, { :multiple => true, :style => "width:100%", :id => "multi", :class => "select2-offscreen", :placeholder => "Select Tags."  } %>

This works to assign tags, but the tags that have already been saved to a listing do not appear in the dropdown on the edit view. For example, if the a user has tagged their listing as "Jim" and "Lucy", they should see this when they arrive on the edit view.

image of desired dropdown

Framework's JS code

The framework is added to the site. In the JS files, it has the following code:

$(document).ready(function(){
      //Dropdown menu - select2 plug-in
      $("#source").select2();

      //Multiselect - Select2 plug-in
      $("#multi").val(["Jim","Lucy"]).select2();

This is excellent starting logic, but obviously I don't want "Jim" "Lucy" manually coded into my dropdowns. How can I override this in js to make it work correctly for the existing tags?

{:selected => @listing.tags.map(&:id).map(&:to_i)}
Was it helpful?

Solution

I just had to go into the plugin's files and change the code to:

$(document).ready(function(){
     //Dropdown menu - select2 plug-in
     $("#source").select2();

     //Multiselect - Select2 plug-in
     var multi = $("#multi");
     var selected = multi.find("option[selected]").map(function() { return this.value; });
     multi.val(selected).select2();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top