【问题标题】:select2 initSelection for redisplayed the formselect2 initSelection 用于重新显示表单
【发布时间】:2017-07-08 06:06:00
【问题描述】:

我正在使用 Select2-rails '3.5.3,我可以使用远程数据进行搜索并保存它,问题是如何恢复选定的文本(例如,如果用户按下编辑),问题:initSelection 不是当表单加载编辑时触发

下面是我的代码

hotelcheck.coffee

  $('.select2-autocomplete').each (i, e) ->
  select = $(e)
  options = { 
    multiple: false
    width: "98%"
    placeholder: "Type Hotel name"
    minimumInputLength: 3
  }
  options.ajax =
    url: select.data('source')
    dataType: 'json'
    type: "GET"
    quietMillis: 250
    # input untuk program
    data: (term, page) ->
      { q: term, 
      page: page,
      per: 25 }
    results: (data) ->
      { results: $.map(data, (item) ->
        {
          text: item.name
          id: item.id
        }
      ) }
    initSelection: (element, callback) ->
      id = $(element).val()
      if id != ''
        $.ajax('/hotels/' + id + '.json', dataType: 'json').done (data) ->
          selected = 
            id: element.val()
            text: data.name
          callback selected
          return
      return
  options.dropdownCssClass = 'bigdrop'
  select.select2 options

表格显示隐藏字段,我将内容保存到hotel_id

<%= f.hidden_field :hotel_id, data: { source: search_name_hotels_path }, class: "select2-autocomplete", :value => "#{f.object.hotel_id unless f.object.new_record? || f.object.hotel_id.nil? }" %>

ajax 的酒店控制器发送值

def show
  @hotel = Hotel.find(params[:id])
  puts "running fill name"

  respond_to do |format|
    format.json { render json: @hotel }
  end
end
  • 源数据 = 带有字段 ID、名称的酒店表
  • 客户表 = 带有字段 hotel_id 的订单

【问题讨论】:

    标签: ruby-on-rails jquery-select2 select2-rails


    【解决方案1】:

    从this page 看来,initSelection 不应该在 options.ajax 中,而应该在 options 中。我会尝试复制他们的示例并根据您的需要进行编辑。或者更新到4.0.0,这似乎更容易。

    【讨论】:

    • 是的,你说得对,我刚刚将 initselection 移到选项下,它的工作,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2013-09-25
    • 2020-07-07
    • 2015-05-12
    • 2013-04-09
    • 1970-01-01
    • 2017-06-27
    相关资源
    最近更新 更多