如何根据选项类动态过滤select2列表

时间:2016-11-28 13:01:19

标签: jquery-select2 jquery-select2-4

我有一个下拉选择的可选“机会”(我在下面的示例中为id="opportunities"),我使用select2 jquery plugin进行了增强,并希望动态过滤此列表以减少可能出现的选项使用第二个选择下拉列表的用户(下例中为id="group-select"),

<label>
  Select an opportunity<br>
  <select id="opportunities" style="width:300px;" multiple="multiple" name="selected-opps" value="">
    <optgroup label="Class A">
      <option class="group-1" value="1a">Opportunity 1a</option>
      <option class="group-2" value="2a">Opportunity 2a</option>
    </optgroup>
    <optgroup label="Class B">
      <option class="group-1" value="1b">Opportunity 1b</option>
      <option class="group-2" value="2b">Opportunity 2b</option>
    </optgroup>
    <optgroup label="Class C">
      <option class="group-1" value="1c">Opportunity 1c</option>
      <option class="group-2" value="2c">Opportunity 2c</option>
    </optgroup>
  </select>
</label>
<select id="group-select">
  <option value="">Select a group</option>
  <option value="group-1">group 1</option>
  <option value="group-2">group 2</option>
</select>
</div>
<div id="select-opportunity"></div>
<script type="text/javascript">
(function( $ ) {
  'use strict';

   var opportunities = $('select#opportunities').select2({
    dropdownParent: $('#select-opportunity')
  });
})( jQuery );
</script>

我希望能够在第二个选择中进行选择,比如说'组1',并希望select2列表仅包含'group-1'项目,因为第一个选择下拉列表中的选项包含{ {1}}类属性。

2 个答案:

答案 0 :(得分:2)

我设法使用select2插件提供的2个可选功能来解决这个问题,即能够使用templating functionality控制项目的构建和显示方式,并使用插件中公开的programmatic control 。我用,

替换了问题中示例下面附带的javascript
grouo-1

我还在底部添加了一个空的<script type="text/javascript"> (function( $ ) { 'use strict'; var opportunities = $('select#opportunities').select2({ dropdownParent: $('#select-opportunity'), templateResult: formatItem }); function formatItem (state) { if (!state.id) { return state.text; } //change the id of our select2 items state._resultId = state._resultId+'-'+state.element.className; var $state = $( '<span class="opportunity-item ' + state.element.className + '">' + state.text + '</span>' ); return $state; } $('select#group-select').change( function() { //hide the unwanted options var group = $('select#group-select option:selected').val(); //clear the styling element $('style#select2-style').empty(); if(group){ //if a group is selected we need to hide all the others $('select#group-select option').not(':selected').each(function(){ group = $(this).val(); if(group){ $('style#select2-style').append( 'li[id$="'+group+'"]{display:none;}' ); } }); } //force the select2 to referesh by opening and closing it again opportunities.select2('open'); opportunities.select2('close'); }); })( jQuery ); </script> <style id="select2-style"></style> 元素,我在其中动态创建隐藏不需要的项目所需的规则。

逻辑

上面的代码创建了模板函数<style>,select2插件将使用它来格式化项目。项目formatItem对象将传递给函数,该函数包含每个项目的唯一state

通过附加相应选项元素的类来修改此id

如果在第二个下拉列表中选择了一个组选项(id),则会创建一组样式并将其附加到底部#group-select元素以隐藏其<style>个属性的所有元素以隐藏的类名结束,例如,如果一个选择了组-1,代码将创建一个样式来隐藏组-2项,

id

然而,为了实现这一点,我们需要强制select2下拉列表进行刷新以获取新的样式,我发现这项工作的唯一方法是使用插件的程序控制来“打开”并立即“关闭” select2下拉列表。

答案 1 :(得分:0)

  

简短示例。

window.templateResult = function templateResult(state) {
            if (state.text.indexOf('ss') == -1)
                return null;///hide

            if (!state.id) { return state.text; }
            var $state = $(
              '<span>' + state.text + '</span>'
            );
            return $state;
        };

        //Init
        $("#select1").select2({
            templateResult: templateResult
        });

以下完整示例。

$(document).ready(function () {

            //general custom filter
            window.Select2FilterFunc = function (state) { return "Default" };

            //general custom templateResult
            window.templateResult = function templateResult(state) {

                //call custom filter
                var result = Select2FilterFunc(state);
                if (result != "Default")
                    return result;

                if (!state.id) { return state.text; }
                var $state = $(
                  '<span>' + state.text + '</span>'
                );
                return $state;
            };

            //Init
            $("#select1").select2({
                templateResult: templateResult
            });

            //Add Custom Filter when  opening
            $('#select1').on('select2:opening', function (evt) {

                //set your filter
                window.Select2FilterFunc = function (state) {
                    if (state.text.indexOf('ss') == -1)
                        return null;//hide item
                    else
                        return "Default";
                };

            }).on('select2:close', function (evt) {
                window.Select2FilterFunc = function (state) { return "Default" };
            });

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="select1" class="js-states form-control" style="width:300px" multiple="multiple ">
        <optgroup label="Alaskan/Hawaiian Time Zone">
            <option value="AK" title="11111111">Alaska</option>
            <option value="HI" title="2222">Hawaii </option>
        </optgroup>
        <optgroup label="Pacific Time Zone">
            <option value="CA">California</option>
            <option value="NV">Nevada</option>
            <option value="OR">Oregon</option>
            <option value="WA">Washington</option>
        </optgroup>
        <optgroup label="Mountain Time Zone">
            <option value="AZ">Arizona</option>
            <option value="CO">Colorado</option>
            <option value="ID">Idaho</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NM">New Mexico</option>
            <option value="ND">North Dakota</option>
            <option value="UT">Utah</option>
            <option value="WY">Wyoming</option>
        </optgroup>
        <optgroup label="Central Time Zone">
            <option value="AL">Alabama</option>
            <option value="AR">Arkansas</option>
            <option value="IL">Illinois</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="OK">Oklahoma</option>
            <option value="SD">South Dakota</option>
            <option value="TX">Texas</option>
            <option value="TN">Tennessee</option>
            <option value="WI">Wisconsin</option>
        </optgroup>
        <optgroup label="Eastern Time Zone">
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="IN">Indiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="OH">Ohio</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WV">West Virginia</option>
        </optgroup>
    </select>