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.
source share