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.
The code below also solves otherwise
The correct way to do this as of v4 is:
$('.select2-chosen').select2('data')[0].text
It is undocumented so could break in the future without warning.
You will probably want to check if there is a selection first however:
I finally figured it out doing this:
if you also want the value:
This one is working fine using V 4.0.3
As of Select2 4.x, it always returns an array, even for non-multi select lists.
For Select2 3.x and lower
Single select:
Note that when there is no selection, the variable 'data' will be null.
Multi select:
From the 3.x docs:
Again I suggest Simple and Easy
Its Working Perfect with ajax when user search and select it saves the selected information via ajax