Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the values in a Select2 dropdown?

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

I have applied Select2 to a input type = hidden, and then populated it using Ajax.

Now at one instance I need to get all the values that are appearing in the dropdown.

Here is a input field.

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

and to this input field I have 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);
    }
});

The yuyu is a json coming from some AJAX call and populating the Select2.

Now I want in some other code a way to get all the values inside the Select2.

like image 277
sushil bharwani Avatar asked Apr 24 '13 08:04

sushil bharwani


1 Answers

I was trying to figure this out myself and found that you can get at least the options in a select2.

var options = $("#dropdown").find("option")
var optionsText = $("#dropdown").find("option[value='1']").text()
like image 138
Alao Avatar answered Sep 18 '22 18:09

Alao