简体   繁体   中英

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

您可以通过以下方式获取当前所选项目的文本值:

$('#id').select2('data').text

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM