Select2 undefined problem

The following function retrieves json data from a URL and populates the select element with jQuery. I use Select2 to convert it to a field with an autocomplete function.

Everything works fine except for the "undefined" entry that I get as soon as the selection items are displayed. Autofill and drop work fine. I tried using a data placeholder, even adding an empty "option" element, but was unsuccessful.

function CitiesList(callback){ $.getJSON(document.URL+'getCities/sdfsfs', function(data){ var html = ''; var len = data.length; var option = '<option></option>'; for (var i = 0; i< len; i++) { html += '<option value="' + data[i] + '">' + data[i] + '</option>'; } $('.select_cities select').append(option); $('.select_cities select').append(html); if(callback && typeof callback == 'function'){ callback.call(null); } }); } <select data-placeholder="Select a city" name="cities" id="cities"> </select> 

'select_cities' is the wrapper of a div around a select element.

+6
source share
5 answers

Now it works in 4.0. The message sent to the result formula can be configured either in the object (see their example GitHub repo.text ) or hardcoded in the function called from the templateResult property. eg:.

 templateResult: formatResult, 

// ...

 function formatResult (result) { if (result.loading) return "Searching..."; 

The configuration wasn’t the easiest to search, since the search string "Searching..." in their example GitHub had zero images, but the retrospective is pretty intuitive.

+12
source

I came across this recently. It seems that new versions of Select2 have problems when the default parameter is set without the corresponding value or when value is an empty string, for example:

 <option value="" selected="selected">Select something</option> 

Either explicitly specify a non-empty value, for example value="0" , or set placeholderOption: 'first' to force Select2 to use the first default parameter:

 $('#select2-field').select2({ placeholderOption: 'first' }); 
+10
source

This problem was addressed in the latest version (3.4.2) of select2. Update, and you should be fine!

+2
source

I investigated this error and found that the formatSelection call can have its data parameter as an array or data object.

To fix this problem, edit the formatSelection function in formatSelection file as follows:

 formatSelection: function (data, container, escapeMarkup) { var dataElement = data ? (data[0] || data) : null; return dataElement ? escapeMarkup(dataElement.text) : undefined; } 

This should fix this nasty bug and get you back on track.

0
source

Add the following line to your script, this should work.

 <script> $(document).ready(function() { $("select").select2(); }); </script> 
-1
source

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


All Articles