Reputation: 618
I have this code for select2 tags method using ajax:
json data:
[
{
"id": "5",
"text": "laravel3"
},
{
"id": "4",
"text": "laravel2"
}
]
Code:
$(document).ready(function(){
$('#tag_list').select2({
placeholder: "Choose tags...",
tags: true,
minimumInputLength: 3,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
ajax: {
url: '/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
};
},
delay: 250,
cache: true
}
});
});
With my code I can search and select data from database or add new tag to my select2 area. Now when I select data from database, <option value="">
is data id
but when I add new tag <option value="">
is name
(text) like this:
Now I need to change option value
(get database data) from data id
to data name
(text). How do change option data value from id to name?!
Upvotes: 2
Views: 2749
Reputation: 12022
Try this:
ajax: {
url: '/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
//updated
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.id, //id part present in data
text: item.text //string to be displayed
});
});
return { results: newData };
},
//
delay: 250,
cache: true
}
Upvotes: 1
Reputation: 14510
Update: I've added more background and references to the docs, and switched the JSFiddle to using $.map()
as the docs do.
The Select2 data format is described in the docs:
Select2 expects a very specific data format [...] Select2 requires that each object contain an
id
and atext
property. [...] Select2 generates thevalue
attribute from theid
property of the data objects ...
The docs also describe how to use something other than your id
:
If you use a property other than
id
(likepk
) to uniquely identify an option, you need to map your old property toid
before passing it to Select2. If you cannot do this on your server or you are in a situation where the API cannot be changed, you can do this in JavaScript before passing it to Select2
In your case, this would mean transforming the data
you get back from your AJAX call, so that the id
element of each result is actually the text
value.
You can do that with the processResults()
AJAX option. To do that using $.map
as the docs do:
processResults: function (data) {
return {
// Transform data, use text as id
results: $.map(data, function (obj) {
obj.id = obj.text;
return obj;
})
};
}
Here's a working JSFiddle. Note I've set it up to simulate your real AJAX request using JSFiddle's /echo/json
async option.
And here's a screenshot of the generated source, showing the value
of both added tags, and those retrieved via AJAX, are the name (text
):
Upvotes: 3