skip to Main Content

Lets say I have item1,item2,item3 pre selected, how do i allow the user to delete only item3 and hide the X delete button from the others.
Thanks in advance

2

Answers


  1. Chosen as BEST ANSWER

    Not the best approach because I should not rely on the option label since it may not be unique but this is the only solution I got.

    Let's say I have a select like this

    <select name="" id="" multiple>
            <option selected value="1">item 1</option>
            <option selected value="2">item 2</option>
            <option value="3">item 3</option>
            <option value="4">item 4</option>
          </select>
    

    and you want the selected values to be unclearable, u can achieve this with this simple code:

    import "./style.css";
    import $ from "jquery";
    import select2 from "select2";
    import "select2/dist/css/select2.min.css";
    select2($);
    // list of excluded items labels
    const excludedItemsTitles = ["item 1", "item 2"];
    //disable selected items function
    const disbaleSelectedItems = function () {
      $(".select2-selection__choice").each(function () {
        //get the list item title
        const currentItemTitle = $(this).attr("title");
        //check if current item title on the array
        if (excludedItemsTitles.includes(currentItemTitle)) //remove delete button
          $(this).children("button.select2-selection__choice__remove").remove();
      });
    };
    $(() => {
      $("select").select2();
    //calling it here so it disables the options u want on the initial load
      disbaleSelectedItems();
    /* 
      this is required because select2 reRender everytime a change occur
      so u have to disable options again
    */ 
      $("select").on("change", disbaleSelectedItems);
    });
    
    

    u can also use the data-unclearable attribute for example on the options u want do not want them to be clearable, and check if the attribute is there.


  2. You can have a property(say canDelete – which should be populated before you render the items in UI) for the items which will identify if a particular item can be deleted or not and based on the flag you can show or hide the "X" button.
    Also if you can share the code which you have tried, it would be easier to understand your question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search