문제

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)}
도움이 되었습니까?

해결책

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top