Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 jquery - How to get text in selectbox

I have input text like

<input type="hidden" name="xa" id="xa" data-placeholder=".." style ="width: 360px;"/>

and i using select2

$("#xa").select2({...});

now, i want to get text when i press 'get text'

$("#gettext").click(function () {
    alert($('#xa').val());  // or $('#xa').select2("val");
});

But it get the id of text. It's not text. How can i do it. thanks

like image 362
DeLe Avatar asked Dec 04 '22 11:12

DeLe


2 Answers

You can get the text value of the currently selected item by:

$('#id').select2('data').text
like image 99
DerMarcus Avatar answered Dec 27 '22 10:12

DerMarcus


Select2 creates a data- attribute for internal purpose, were it stores some necessary information like id,selected value of select2 instance. this can used to extract selected value.

Select2 Community : Each element instantiated as a select2 component must contain id and text keys.

var id = $(test).select2('data').id;

var seletedVal = $(test).select2('data').text;

Update : With Latest version of Select2 , the object is stored in a array,so the text has to be accessed as below (jsfiddle link updated as well).

$(test).select2('data')[0].text //instead of $(test).select2('data').text

thanks for update @DiMono

Live Demo @ JSFiddle

Happy Coding :)

like image 22
dreamweiver Avatar answered Dec 27 '22 11:12

dreamweiver