$('input[name="airport"...">

Select2: set the value of the hidden field

I have the following code:

<input type="hidden" name="airport" tabindex="6" /> $('input[name="airport"]', '#details-form').select2({ minimumInputLength: 3, multiple: true, separator: ';', width: 'off', initSelection : function (element, callback) { var data = []; $(element.val().split(';')).each(function () { data.push({id: this, text: this}); }); callback(data); }, ajax: { url: History.getBasePageUrl() + 'get-airports-dictionary', dataType: 'json', data: function (term, page) { return { q: term }; }, results: function (data, page) { var code = parseInt(data[0]); switch (code) { case 0: return {results: data[1]}; break; default: window.Common.showError(data[1]); break; } } }, formatResult: formatAirportResult, formatSelection: formatAirportSelection }); 

Everything works fine until I want to set an existing value for this field. The element argument inside the initSelection method shows an empty value!

 $('input[name="airport"]', '#details-form').select2('val', '2'); 

I tried to set the original value with the following code:

 $('input[name="airport"]', '#details-form').val('2'); 

This works, but somewhere inside the select2 val method, the value disappears.

I am using version 3.4.0 of Select2 with this update .

thanks

+4
source share
1 answer

Here is a working solution:

 $('input[name="airport"]', '#details-form').select2({ minimumInputLength: 3, multiple: true, separator: ';', width: 'off', initSelection : function (element, callback) { var data = []; $(element.val().split(',')).each(function(i) { var item = this.split(':'); data.push({ id: item[0], label: item[1] }); }); callback(data); }, ajax: { url: History.getBasePageUrl() + 'get-airports-dictionary', dataType: 'json', data: function (term, page) { return { q: term }; }, results: function (data, page) { var code = parseInt(data[0]); switch (code) { case 0: return {results: data[1]}; break; default: window.Common.showError(data[1]); break; } } }, formatResult: formatAirportResult, formatSelection: formatAirportSelection }); function formatAirportResult(item) { return item.label + ' <strong class="pull-right">' + item.code + '</strong>'; } function formatAirportSelection(item) { return item.label; } 

I don't know why, but the value argument cannot be a string - to make it work, it must be an array of strings. Otherwise, select2 sets an empty value in the input field.

 $('input[name="airport"]', '#details-form').select2('val', ['2:Domodedovo', '3:Vnukovo']); 

Proof - http://jsfiddle.net/GZyeb/1/

+7
source

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


All Articles