Dynamic select2 options using api


Dynamic select2 options using api



I'll try to explain my problem as much as I can. I am trying to create, with select2 plugin, a way for the user to write some letters and on each letter pressed a call to an API that gives the first 20 results given by that API.


select2



So I have my HTML select :


<select name="filtre_products" class="form-control products-select2" multiple>

</select>



And then my JS (it's commented) :


$(".products-select2").select2({
width: '100%',
closeOnSelect: false,
placeholder: '',
minimumInputLength: 3,
query: function (query) {
var data = {results: }, i, j, s;
if(query.term != null) {
var ajax_r = ;
$.ajax({
url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
success: function(data_a){
//Getting the data
data_a = JSON.parse(data_a);

//Looping through the each data and putting them inside a table
data_a.forEach( (e) => {
ajax_r.push(e);
});

//Filtering the data to get from it the id and the text to be used
ajax_r.forEach( (e) => {
var tmp = e.split('-');
var id = tmp[0];
var name = tmp[2];

data.results.push({value: id, text: name});
});

query.callback(data);
}
});
}
},
//Sending the results to the function to modify the options as I please
templateResult: formatResult
});



And this is the formatResult function I use :


formatResult


function formatResult(d) {
if(d.loading) {
return d.text;
}

// Creating an option of each id and text
$d = $('<option/>').attr({ 'value': d.value }).text(d.text);

return $d;
}



My problem is that select2 is supposed to be creating the options dynamically upon initialization and thus actually creating <li> out of the options and adding to them dynamically id's and such. But in the way I'm creating it, it's putting the options INSIDE the <li> tags which is not what I want, I want it to treat it as dynamic options like he does without the query call.


select2


<li>


<li>



Some doc sources for you guys, it shows a part of what I'm trying to do, but the example shows how to show results from what we write, I want it to show from the api upon each click, and of course having multiple select added :
http://select2.github.io/select2/#data




2 Answers
2



I've read the documentation and found that the ajax support seems to fit your needs.



In your select2 options object, add an ajax object. Inside this ajax object :


ajax


ajax


results



Then, you can reuse your templating function.



Here's a working snippet with a random API. Please note the query's term doesn't impact the returned data.




$(document).ready(function () {

$(".products-select2").select2({
width: '100%',
closeOnSelect: false,
placeholder: '',
minimumInputLength: 3,
ajax: {
url: "https://jsonplaceholder.typicode.com/users",
dataType: 'json',
delay: 250,
data: function (query) {
// add any default query here
return query;
},
processResults: function (data) {
// Tranforms the top-level key of the response object from 'items' to 'results'
var results = ;
data.forEach(e => {
results.push({ id: e.id, text: e.name });
});

return {
results: results
};
},
},
templateResult: formatResult
});

function formatResult(d) {
if(d.loading) {
return d.text;
}

// Creating an option of each id and text
$d = $('<option/>').attr({ 'value': d.value }).text(d.text);

return $d;
}

});


<html>
<head>
https://code.jquery.com/jquery-3.3.1.min.js

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.full.js
</head>
<body>

<select name="filtre_products" class="form-control products-select2" multiple>
</select>

</body>
</html>



For your ajax success call, do this or similar. i think you don't require such big code. below code snippet is from my working script.


success: function (data) {

var dbSelect = $('#ddlItems'); // id for Dropdown list
dbSelect.empty();
result = JSON.parse(data);
// Parse result object and create your array collection in ajax_r object
for (var i = 0; i < ajax_r.length; i++) {
dbSelect.append($('<option/>', {
value: ajax_r.item[i].Value,
text: ajax_r.item[i].Text
}));
}
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift