简体   繁体   English

如何在select2事件中获取所有选项数据?

[英]How to get all options data in select2 event?

Here is my code: 这是我的代码:

$(document).find('#mySelect').on('select2:select', function(){
    console.log($(this).val());
    console.log($(this).allOptions);
})

I am getting the selected value here. 我在这里得到选定的值。 I want to access all the options here. 我想在这里访问所有选项。 how to do that? 怎么做?

use $(this).children() . 使用$(this).children()

 $(document).find('#mySelect').on('change', function() { console.log($(this).val()); console.log($(this).children()); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select name="" id="mySelect"> <option value="One">One</option> <option value="Two">Two</option> </select> 

You can try like this: 您可以这样尝试:

$(document).find('#example').on('select2:select', function(){
   var data = [],
   adapter = $(this).data().select2.dataAdapter;
    $(this).children().each(function () {
        if (!$(this).is('option') && !$(this).is('optgroup')) {
            return true;
        }
        data.push(adapter.item($(this)));
    });
    console.log(data)
})

HTML look like: HTML看起来像:

<select id="example" multiple="multiple" style="width: 300px">
    <option value="JAN">January</option>
    <option value="FEB">February</option>
    <option value="MAR">March</option>
    <option value="APR">April</option>
    <option value="MAY">May</option>
    <option value="JUN">June</option>
    <option value="JUL">July</option>
    <option value="AUG">August</option>
    <option value="SEP">September</option>
    <option value="OCT">October</option>
    <option value="NOV">November</option>
    <option value="DEC">December</option>
</select>

You may check it on fiddle also. 您也可以在小提琴上检查它。 Here is the link demo 这是链接演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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