Question

I'm using two select2 in my form and if i choose a first select2 it will load a data from the server then populate second select2 from the data received. the problem is its not populating second select2 anyone knows here how to solve it?

I tried following code but no luck :(

firstSelection = $('#first_id').select2( allowClear: false )
secondSelection = $('#second_id').select2(
  allowClear: false
)

firstSelection.on('select2-selecting', (e)->
  if e.val
    $.get(
      "/api/v1/posts/#{e.val}",
      (data)-> (
        console.log data
        secondSelection.select2("data", data)
      )
    )
)
Était-ce utile?

La solution

You'll need to reinitialize the second select2 element after you receive the data result from the first select2's ajax call. Something like this should work:

firstSelection = $('#first_id').select2( allowClear: false )
secondSelection = $('#second_id')

firstSelection.on('select2-selecting', (e)->
  if e.val
    $.get(
      "/api/v1/posts/#{e.val}",
      (data)-> (
        console.log data
        newOptions = data

        select = secondSelection
        if select.prop
          options = select.prop("options")
        else
          options = select.attr("options")
        $("option", select).remove()
        $.each newOptions, (val, text) ->
          options[options.length] = new Option(text, val)
        secondSelection.select2()
      )
    )
)

The basic mechanics are to create options from your data, add them to the secondSelection element, and then initialize select2 again on that element.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top