How to get all the values ​​in the Select2 popup menu?

How can we get all the elements that are in the jQuery Select2 dropdown plugin.

I applied Select2 to the input type = hidden and then populated it with Ajax.

Now in one instance, I need to get all the values ​​that appear in the drop-down list.

Here is the input field.

<input type="hidden" id="individualsfront" name="individualsfront" style="width:240px" value="" data-spy="scroll" required />

and in this input field I applied this

$("#individualsfront").select2({
    multiple: true,
    query: function (query){
        var data = {results: []};
        $.each(yuyu, function(){
            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                data.results.push({id: this.id, text: this.text });
            }
        });
        query.callback(data);
    }
});

Yuyu is json coming from some kind of AJAX call and populating Select2.

Now I want that in some other code I could get all the values ​​inside Select2.

+5
source share
3 answers

option 1: you can directly use the objectdata

var results = [];
$("#individualsfront").select2({
    multiple: true,
    query: function (query){
        var data = {results: []};
        $.each(yuyu, function(){
            if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                data.results.push({id: this.id, text: this.text });
            }
        });

        results = data.results; //<=====  
        query.callback(data);
    }
});

and use it as follows:

$('#individualsfront').on('open',function(){
    $.each(results, function(key,value){
        console.log("text:"+value.text);
    });
});

2: () - :

$('#individualsfront').on('open',function(){
    $(".select2-result-label").each(function()
        {
            console.log($(this).text());
        })
    });
});

http://jsfiddle.net/ouadie/qfchH/1/

3: .select2("data");, , .

var arrObj = $("#individualsfront").select2("data");
for each(yuyu in arrObj)
{
   console.log("id: "+yuyu.id+ ", value: "+yuyu.text);
}

a >

+2

, select2.

var options = $("#dropdown").find("option")
var optionsText = $("#dropdown").find("option[value='1']").text()
0
function select2Options($elementSelect2) {
    var data = [],
        adapter = $elementSelect2.data().select2.dataAdapter;
    $elementSelect2.children().each(function () {
        if (!$(this).is('option') && !$(this).is('optgroup')) {
            return true;
        }
        data.push(adapter.item($(this)));
    });
    return data;
}
0
source

All Articles