Select2: Hide certain options dynamically

前端 未结 10 794
情深已故
情深已故 2020-12-03 06:56

Basically what I\'m looking for is the ability to hide options from the dropdown of select items. So, technically they would still be options, but you just wouldn\'t be able

10条回答
  •  半阙折子戏
    2020-12-03 07:08

    I just invested 3 hours and found a very clean and easy solution for me dynamically showing/hiding options in a select2-container.

    First, I create the select2 with this option:

    $( selector ).select2({
      templateResult: resultState
    });
    

    Then I provide the resultState callback function which copies all classes from the original to the select2-option. This allows us to show/hide options in select2 depending on the class we assign to the original option.

    function resultState(data, container) {
        if(data.element) {
            $(container).addClass($(data.element).attr("class"));
        }
        return data.text;
    }
    

    In my css I declared this line:

    .select2-container .select2-results__option.optInvisible {
        display: none;
    }
    

    Now I can easy show or hide hide any options in the select2-container by adding the optInvisible class to the :

    
    

    Or you could also update it dynamically using addClass("optInvisible") or removeClass("optInvisible").

    May this helps anyone ;) Greetings

提交回复
热议问题