Friday 29 June 2018

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.

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 :

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.

Some doc sources for you guys : http://select2.github.io/select2/#data



from Dynamic select2 options using api

No comments:

Post a Comment