简体   繁体   English

当已经选择了选择选项时发生事件触发器Select2(多个选择选项)

[英]Event Trigger Select2 when the select option is already selected (Multiple Select Option)

I have a few select option like this : 我有几个这样的选择选项:

<select class="competence">
    <option>Android</option>
    <option>PHP</option>
    <option>RoR</option>
    <option>Javascript</option>
</select>

and I want the option is disabled when the option is already selected in another select option. 并且我希望在另一个选择选项中already selected该选项时禁用该选项。

my jquery look like this : 我的jQuery看起来像这样:

$('select.competence').on('change', function () {
    $('option').prop('disabled', false);
    $('select.competence').each(function () {
        var val = this.value;
        $('select.competence').not(this).find('option').filter(function () {
            return this.value == val;
        }).prop('disabled', true);
    });
});

everything is works fine, until i tried to use select2 plugin, so when i used $('select.competence').select2() , the disabled function is not work, i think the selector is wrong. 一切正常,直到我尝试使用select2插件,所以当我使用$('select.competence').select2()disabled功能不起作用,我认为选择器是错误的。

As far as I know, you would have to selector.select2('destroy') and then reinitialize the select2 see if this is what you were asking for, I assume that you have multiple selects with same value options. 据我所知,您将必须selector.select2('destroy') ,然后重新初始化select2,看看这是否是您要的,我假设您有多个具有相同值选项的选择。

 $(document).ready(function() { $('.competence').on('change', function() { var allSelects = $('.competence'); allSelects.find('option').prop('disabled', false); allSelects.each(function() { var currSelect = $(this); allSelects.not(currSelect).find('option').each(function() { if ($(this).val() == currSelect.val()) { $(this).prop('disabled', true); } }); }); $('.competence').select2("destroy").select2(); }); $(".competence").select2(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet" /> <select class="competence"> <option value='android'>Android</option> <option value='php'>PHP</option> <option value='ror'>RoR</option> <option value='javascript'>Javascript</option> </select> <select class="competence"> <option value='android'>Android</option> <option value='php'>PHP</option> <option value='ror'>RoR</option> <option value='javascript'>Javascript</option> </select> <select class="competence"> <option value='android'>Android</option> <option value='php'>PHP</option> <option value='ror'>RoR</option> <option value='javascript'>Javascript</option> </select> 

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

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