0

cocoon を使用する Rails アプリがあります

= link_to_add_association

部分形式を呼び出す

メインフォームには、select2要素のすべてのデータをロードするためのコーヒースクリプトがあります

ajaxパーシャルが挿入されると、select2要素は表示されません。インスタンス化する必要があります。

これは私のフォームのcoffee/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

ページ上のすべての要素が更新されます。当然のことながら、すべての select2 オブジェクトを呼び出します。私はselect2 js用にこのコードを書きませんでした。

既存のフォーム要素はすべて問題ありませんが、動的に追加された要素は更新されるため、値が失われます。

追加した要素だけを選択して動作させたい。

私が試したら

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

どちらも機能しません

多くのオプションを試しましたが、私の髪は薄くなり、助けが必要です. JSは私の大敵です。本当に面倒です.....

ヘルプ!

4

1 に答える 1

-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

ああ、神様。これに何時間もかかった後、私はそれを手に入れました....

于 2014-09-10T18:17:20.317 に答える