Set initial value on select2 ajax rails

I'm trying to make it work

I have a rail form that looks like this:

%tr %td = f.label :company %td = f.hidden_field :companyid, class: 'select2 ajax', data: { source: companies_path } 

inside my 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.dropdownAutoWidth = "true" select.select2 options return 

The search works fine, the data storage also, but when I open the page again, that is, edit the saved record, I get an empty select2 object without the default value loaded in the select box.

It does not collect the existing value from the saved record and does not display it. I can search without problems - everything is in order, it just does not work.

Now I played with InitSelection and tried to set "val", but it just didn't work.

What is the correct way to load a value stored from a record into select2?

thanks

DECISION FROM EMAILENIN TO SEE BELOW

 $(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.dropdownAutoWidth = "true" options.initSelection = (element, callback) -> data = {id: element.val().split('||')[0], text: element.val().split('||')[1]}; callback data select.select2 options return 
+5
source share
1 answer

To set the initial value, set the value directly in the hidden field during page load.

 %tr %td = f.label :company %td = f.hidden_field :companyid, value: "#{@company.id}||#{@company.name}", class: 'select2 ajax', data: { source: companies_path } 

And then in javascript use this value and set the desired dropdown value:

 initSelection: (element, callback) -> data = [] $(element.val().split(",")).each -> data.push id: this.split('||')[0] text: this.split('||')[1] $(element).val('') callback data 

Here I saved the identifier and value divided by || and each ID / value pair is separated by a comma. Mine is a multiple-choice drop-down list. You can change this for a single choice drop-down list, as shown below:

 initSelection: (element, callback) -> data = {} data.id = $(element).val().split('||')[0] data.text: $(element).val().split('||')[1] $(element).val('') callback data 

The key note here is that you need to call the callback method with the data object that you want to set.

+2
source

Source: https://habr.com/ru/post/1201497/


All Articles