Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Selected Text from select2 when using <input>

I am using the select2 control, loading data via ajax. This requires the use of the <input type=hidden..> tag.

Now, I want to retrieve the selected text. (The value property in the data-bind expression sotres the id only)

I have tried $(".select2-chosen").text(), but this breaks when I have multiple select2 controls on the page.

like image 693
robasta Avatar asked Nov 06 '13 14:11

robasta


People also ask

How do I get Select2 data?

Using the data methodCalling select2('data') will return a JavaScript array of objects representing the current selection. Each object will contain all of the properties/values that were in the source data objects passed through processResults and templateResult callbacks.

How do I create a Select2 dynamically?

Select2 jQuery plugin is easy to add on the <select > element. Need to call the select2() method on the selector to initialize. If you adding select2 on a class or select element and when you add an element dynamically then select2 is not initialized on that element.

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


1 Answers

As of Select2 4.x, it always returns an array, even for non-multi select lists.

var data = $('your-original-element').select2('data') alert(data[0].text); alert(data[0].id); 

For Select2 3.x and lower

Single select:

var data = $('your-original-element').select2('data'); if(data) {   alert(data.text); } 

Note that when there is no selection, the variable 'data' will be null.

Multi select:

var data = $('your-original-element').select2('data') alert(data[0].text); alert(data[0].id); alert(data[1].text); alert(data[1].id); 

From the 3.x docs:

data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.

data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].

like image 185
Moeri Avatar answered Oct 03 '22 06:10

Moeri