ruby-on-railsjquery-select2select2-rails

select2 initSelection for redisplayed the form


I'm Using Select2-rails '3.5.3, I can do search with remote data and save it, the problem is how I can restore the selected text (for example if user press edit), problem: initSelection is not fired when form loaded with edit

below is my code

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

form to show hidden field, I save the content to 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? }" %>

hotel controller for ajax send the value

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

  respond_to do |format|
    format.json { render json: @hotel }
  end
end

Solution

  • From this page, it looks like initSelection should NOT be in options.ajax, but just in options. I would try to copy the example they have and edit it to your needs. OR update to 4.0.0, which seems to be much easier.