I am trying to use jquery-select2, but I am returning json objects that have a different structure. I do not have id and text properties, but Code and Description .
<input type="hidden" id="select2Test" name="select2Test" value=""/>
This is my json object:
[{"Code":"20900","Description":"LONDON"}]
I found sample code on the Internet (and read the docs), but I can't seem to get it to work. This is my javascript:
$("#select2Test").select2({ placeholder: "Search City", minimumInputLength: 2, multiple: false, quietMillis: 5000, id: function (item) { return { id: item.Code }; }, ajax: { url: '/Services/FetchCities', dataType: 'json', type: "POST", data: function (term, page) { return { city: term }; }, results: function (data, page) { return { results: data }; } }, // initSelection: function (item, callback) { // var data = { id: item.Code(), text: item.Description() }; // callback(data); // }, formatResult: function (item) { return ('<div>' + item.Code + ' - ' + item.Description + '</div>'); }, formatSelection: function (item) { return (item.Description); }, escapeMarkup: function (m) { return m; } }).on("change", function () { var $this = $(this); alert($this.val()); });
I applied my unique key here:
id: function (item) { return { id: item.Code }; },
formatted my result here:
formatResult: function (item) { return ('<div>' + item.Code + ' - ' + item.Description + '</div>'); },
and set the choice here:
formatSelection: function (item) { return (item.Description); },
so far so good. everything seems to work, except when I try to read or post a value, I just get a weird result: [object Object] . I think this has something to do with the result function:
results: function (data, page) { return { results: data }; }
but I'm not 100% sure.
PS: if I modify my returned json object using id and text, everything will work fine, but I cannot do this because the other parts of my code use a different link.
Any help would be appreciated.
UPDATE
I found a solution matching a data object:
results: function (data, page) { return { results: $.map(data, function (item) { return { id: item.Code, text: item.Description }; }) }; }
with these changes, I do not need to set the id property:
// id: function (item) { return { id: item.Code }; },
and formatResult and formatSelection
formatResult: function (item) { return ('<div>' + item.id + ' - ' + item.text + '</div>'); }, formatSelection: function (item) { return (item.text); },
no need to change.
I wonder the best option.