Home > other >  How to hide option in dropdown in select2 after selecting the option
How to hide option in dropdown in select2 after selecting the option

Time:11-23

I have a multiselect select2 dropdown as shown below Original Dropdown after selecting 2 options(A and B),
Options Selected I want only C to be appeared in the option desired output is
Desired Output I am using razor pages in c# with jquery as shown below cshtml:

<select id="selector"
        
        multiple="multiple"
        asp-for="Payload.List"
        asp-items="@(new SelectList(Model.DropDown, "Id", "Name"))">
</select>  

JQuery

$('#selector').on("select2:selecting", function (e) {

    $('#'   e.params.args.data._resultId).css("display", "none");
});

here _resultId has the id of generated options, I wanted to hide the option with that Id. But It is not working can anyone please help

CodePudding user response:

Not sure what is the version of select2 you use. For my project I use select2 latest version 4.1.0-rc.0, just apply the css like below:

@section Scripts
{
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css" integrity="sha512-aD9ophpFQ61nFZP6hXYu4Q/b/USW7rpLCQLX6Bi0WJHXNO7Js/fUENpBQf/ P4NtpzNX0jSgR5zVvPOJp W2Kg==" crossorigin="anonymous" referrerpolicy="no-referrer" />    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js" integrity="sha512-4MvcHwcbqXKUHB6Lx3Zb5CEAVoE9u84qN ZSMM6s7z8IeJriExrV3ND5zRze9mxNlABJ6k864P/Vl8m0Sd3DtQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>    
    <script>
        $("#selector").select2();
    </script>
    <style>
        .select2-results__option--selected {
            display: none;
        }        
    </style>
}

If above css does not work for your project and you use other older version, try to apply the css below:

.select2-results__option[aria-selected=true] { display: none;}
  • Related