Select2 jquery - How to get text in selectbox

自闭症网瘾萝莉.ら 提交于 2020-01-01 12:14:11

问题


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


回答1:


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




回答2:


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

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


来源:https://stackoverflow.com/questions/16301052/select2-jquery-how-to-get-text-in-selectbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!