I'm using Select2 to provide dynamic select functionality on my page.
Here is the code:-
$("#Spon_Index").select2({
placeholder: "Type to select a sponsor",
minimumInputLength: 3,
multiple: false,
width: 400,
ajax: {
url: "../control/autocomplete_sponsor.aspx",
data: function(term) {
return term;
},
results: function(data, page) {
alert(results);
return {
results: data
}
},
formatResult: function(data) {
return data.text;
},
formatSelection: function(data) {
return data.id;
},
escapeMarkup: function(m) {
return m;
}
}
});
Using Fiddler, I can see that I'm getting the correct return from autocomplete_sponsor.aspx, example:-
[{"id":"12","text":"Smiths"},{"id":"118","text":"Dr Smiths"}]
However, nothing is happening with the control at all. It either hangs on 'Searching', or nothing...I've checked the developer tools and there is an error:-
Uncaught TypeError: Cannot read property 'slice' of undefined
I've looked at some other solutions on SO, and tried various refactorings of my code to get this to work but I've now officially run out of ideas....hoping it's something really simple I've missed out.
Select2 just seems to need a Javascript object instead of a JSON string.
The below code is for select2 v4.0.3, so results
was replaced by processResults
.
$("#Spon_Index").select2({
placeholder: "Type to select a sponsor",
minimumInputLength: 3,
multiple: false,
width: 400,
ajax: {
url: "../control/autocomplete_sponsor.aspx",
data: function(term) {
return term;
},
processResults: function(data, page) {
return { results: JSON.parse(data) };
},
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With