How to get the name from the id in select2 combo?

2.1k Views Asked by At

I have select2 ComboBox the data is loaded by Ajax. I am trying to set the default value to the select2 by reading the id from the input value (which is set on the server side) and set it to the select2 programmatically.

I think I should implement the initSelection() function in a way to solve this issue.

Here is my code:

The HTML input is:

<input type="hidden" class="mySelect2" value="01" name="someName" />
The value "01" is set at the server  

The JavaScript is:

$(".mySelect2").select2({
    ajax: {
        url:"data.php",
        dataType:"json",
        data:function(term, page) {
            return {
                query:term, page: page -1
            } ;
        },
        results:function(data, page) {
            return data  
        }
    }
});

I tried this but it did not work .

     $(".mySelect2").select2('val', '01');

And an error occured : "cannot call val() if initSelection() is not defined "

2

There are 2 best solutions below

2
On

try something like this

        $(function(){
            $(".mySelect2").select2({
                ajax: {
                    url:"data.php",
                    dataType:"json",
                    data:function(term, page) {
                        return {
                            query:term, page: page -1
                        } ;
                    },
                    results:function(data, page) {
                        return data  
                    },

                }
            });
            $(".mySelect2").select2('data', {id:'01',text:'01'});
        })

HTML CODE

<input type="hidden" class="mySelect2" style="width:100px;" value="[{id:'01',text:'01'}]" name="someName" />
2
On

The general premise of initialising a default value in a select2 control using ajax can be solved using something like:

initSelection: function (element, callback) {
        var id = $(element).val();
        if (id !== "") {
        $.ajax("data.php", {
            data: {
                id: id // return a single item from your service
            },
            dataType: "json"
        }).done(function (data) {
            var results = [];
            $.each(data, function (index, item) {
                results.push({
                    id: item.Id, // whatever your id field is
                    text: item.TextValue // whatever your text field is
                });
            });
            callback(results[0]);
        });
    }
}

I'm not a PHP person, but this should be standard across ajax requests. The approach basically assumes you can return a single result as well as the list.