2014-09-10 22 views
0

我有一個使用繭一個滑軌應用程序繭SELECT2 AJAX負載 - SELECT2元件犯規負載

= link_to_add_association

調用局部形式

主要形式我有咖啡腳本上加載select2元素的所有數據

當插入ajax部分時,select2元素不會出現。我需要實例化它。

這是我的形式咖啡/ JS

$(document).ready -> 
    $(".select2").each (i, e) -> 
    select = $(e) 
    options = {} 
    if select.hasClass("ajax") 
     options.ajax = 
     url: select.data("source") 
     dataType: "json" 
     data: (term, page) -> 
      q: term 
      page: page 
      per: 10 
     results: (data, page) -> 
      results: data 
     options.placeholder = "Select a value" 
     options.allowClear= "true" 
     options.dropdownAutoWidth = "true" 
     options.initSelection = (element, callback) -> 
     data = {id: element.val().split('||')[0], text: element.val().split('||')[1]}; 
     callback data 
    select.select2 options 
    return 

如果我使用coocon - 插入結合

$('body').bind 'cocoon:after-insert', (e, inserted_item) -> 
    $(".select2").each (i, e) -> 
     select = $(e) 
     options = {} 
     if select.hasClass("ajax") 
     options.ajax = 
      url: select.data("source") 
      dataType: "json" 
      data: (term, page) -> 
      q: term 
      page: page 
      per: 10 
      results: (data, page) -> 
      results: data 
     options.placeholder = "Select a value" 
     options.allowClear= "true" 
     options.dropdownAutoWidth = "true" 
     options.initSelection = (element, callback) -> 
      data = {id: element.val().split('||')[0], text: element.val().split('||')[1]}; 
      callback data 
     select.select2 options 
     return 

我得到的頁面刷新上的所有元素之後 - 當然,我打電話都選擇2對象。我沒有寫這個代碼爲select2 js。

所有現有的表單元素都可以,但是那些動態添加的元素會被刷新 - 所以它們會丟失它們的值。

我想只選擇添加的元素並使其工作。

,如果我嘗試

$('body').bind 'cocoon:after-insert', (e, inserted_item) -> 
    $(inserted_item).find(".select2").select2 
    return 

它不工作,要麼

試了很多的選擇,但我的頭髮現在是瘦,我需要幫助。 JS是我的主要敵人,我真的覺得它很痛.....

幫助!

+0

$(inserted_item).find(「。select2」)。select2 – user1320651 2014-09-10 18:04:58

回答

-1
$(document).ready -> 
    $('body').bind "cocoon:after-insert", (e, inserted_item) -> 
    select=$(inserted_item).find(".select2.ajax") 
    options = {} 
    if select.hasClass("ajax") 
     options.ajax = 
     url: select.data("source") 
     dataType: "json" 
     data: (term, page) -> 
      q: term 
      page: page 
      per: 10 
     results: (data, page) -> 
      results: data 
     options.placeholder = "Select a value" 
     options.allowClear= "true" 
     options.dropdownAutoWidth = "true" 
     options.initSelection = (element, callback) -> 
     data = {id: element.val().split('||')[0], text: element.val().split('||')[1]}; 
     callback data 
    select.select2 options 
    return 

Omg。小時,然後我得到它....