【问题标题】:restore saved / initial value for select2 4.0.3 with rails使用rails恢复select2 4.0.3的保存/初始值
【发布时间】:2023-03-27 23:55:02
【问题描述】:

我正在使用 select2 版本 4.0.3

下面是我使用 select tag rails helper 的 html

<%= f.select(:hotel_id, [], {},  :class => 'select2-autocomplete' ) %>

下面是我的咖啡脚本(为创建新工作)

  $('.select2-autocomplete').select2
  multiple: false
  width: "98%"
  placeholder: "Type Hotel name"
  minimumInputLength: 3
  ajax:
    url: '/hotels/search_name.json'
    dataType: 'json'
    delay: 250
    data: (params) ->
      q: params.term
    processResults: (data, params) ->
      results: $.map data, (item)->
        id: item.id
        text: item.name

之前它使用 initSelection 为 select2 版本 3.5.3 完成,但后来版本 4.0.3 发生了变化,我确实阅读了 documentation 但仍然没有好的结果,

我的问题是当用户编辑页面时,我需要恢复之前的选择值并显示它。

【问题讨论】:

    标签: ruby-on-rails ajax coffeescript select2


    【解决方案1】:

    在下面如何使用 select2 版本 4 恢复值经过反复试验后,它可能不干净,但它可以工作

    <% if f.object.persisted? && f.object.hotel_id  %>
      <% if f.object.hotel_id > 0 %>
        <% value = f.object.hotel_id  %>
        <% text  = Hotel.find(value).name %>
      <% end %>
    <% end %>
    <%= f.select(:hotel_id, options_for_select([["#{text}", value.to_s]]),  {selected: value},  :class => 'select2-autocomplete' ) %>
    

    关键答案是底线,

    • 使用 f.select,
    • 使用 option_for_select 生成选项
    • 确保选项使用字符串 value.to_s
    • 在选项下使用 { selected: value}

    希望它可以帮助其他使用 select2 和 ajax 搜索的 Rails 用户

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 1970-01-01
      • 2023-03-03
      • 2021-04-26
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2016-07-29
      • 2015-05-11
      相关资源
      最近更新 更多