簡體   English   中英

Rails用select2嵌套表單

[英]Rails nested form with select2

我使用cocoon gem作為嵌套表單,並使用select2作為自定義選擇。

第一個集合選擇已按預期工作。 當我添加另一個選擇項時,即使選擇項具有相同的類,它也沒有工作。 我試過這個解決方案。 但它還沒有解決我的問題。 因為我已經調用了部分嵌套項。

_form.html

 <%= simple_form_for(@course) do |f| %>
   <%= f.simple_fields_for :course_teachers do |course_teacher| %>
     <%= render "course_teacher_fields", :f => course_teacher %>
   <% end %>
   <div class="links">
     <%= link_to_add_association 'Add Teacher', f, :course_teachers, class:"btn btn-info" %>
   </div>
 <%end%>

_course_teacher_fields.html

<div class="nested-fields">
  <%= f.association :teacher, collection: Teacher.all, label_method: :full_name_with_title, input_html: {class: "teacher"} %><br/>
</div>

app.js

$(".teacher").select2({
  placeholder: "Select Teacher",
  allowClear: true
});

你有什么主意嗎?

問題是你的javascript只在已經渲染的項目上初始化select2(這就是為什么你沒有第一個選擇的問題)但是在你添加另一個之后, select2()不會觸發而不是在該項目上初始化。

要解決這個問題,請在`cocoon:after-insert'之后添加一個回調並在添加的行上激活select2事件。

所以你的javascript會是這樣的

function init_select2(selector){
  $(selector).select2({
    placeholder: "Select Teacher",
    allowClear: true
  });
};

init_select2(".teacher")

$("form").on("cocoon:after-insert", function(_, row){
  field = $(row).find(".teacher")
  init_select2(field);
});

我沒有測試過這段代碼,但我希望你能得到這個想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM