我试图找出在select2下拉项目中读取当前所选文本(不是值)的正确方法.我看不到这个列出
on the documentation.
我可以看到有一个新的DOM元素是具有“-container”后缀和“select2-”前缀的原始选择下拉列表的ID,所以不知道这是推荐读取还是select2有另一个api调用.
使用jquery读取当前所选文本的正确方法是什么?
解决方法
只需使用这个答案的细节:
How to get Selected Text from select2 when using <input>
How to get Selected Text from select2 when using <input>
像这样:
$(function() { // Initialise $('.example-basic-single').select2(); $('.example-basic-multiple').select2(); // Retrieve default selected value var defaultSelection = $('.example-basic-single').select2('data'); $("#selectedS").text(defaultSelection[0].text); // Single select capture $('.example-basic-single').on("select2:select",function (e) { var data = $(this).select2('data'); $("#selectedS").text(data[0].text); }); $('.example-basic-multiple').on("select2:select",function (e) { var data = $(this).select2('data'); var selectedText = $.map(data,function(selected,i) { return selected.text; }).join(); $("#selectedM").text(selectedText); }); $('.example-basic-multiple').on("select2:unselect",i) { return selected.text; }).join(); $("#selectedM").text(selectedText); }); });
.demo { margin: 10px; } .labelS,.labelM { margin-top: 5px; } .selection { margin-top: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://select2.github.io/dist/js/select2.full.js"></script> <link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="col-xs-4"> <div class="selection">Single select:</div> <select class="example-basic-single form-control"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <div class="labelS">Selected:</div> <div id="selectedS"></div> </div> <div class="col-xs-4"> <div class="selection">Multiple Select:</div> <select class="example-basic-multiple form-control" multiple="multiple"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> <option value="5">Five</option> </select> <div class="labelM">Selected:</div> <div id="selectedM"></div> </div> </div> </div>