javascriptjqueryjquery-select2select2-rails

How to reset specific selected option in select2


For example i have 2 records pre-selected as seen in screenshot below.

I noticed that aria-selected="true" for selected ones.

How can I find it by title and remove/reset it so it will not be part of current selected items.

Thanks in advance.

enter image description here


Solution

  • select2 has link to particular <select> element in DOM. So, first you need to change select option, and then trigger change event of select2
    For change option text you can like this

    <select id="mySelect">
      <option value="option1">Text</option>
    </select>
    
    var $select2 = $("#mySelect").select2();
    $('#mySelect option[value="option1"]').text = 'Another text';
    

    And then trigger change event for select2:

    $select2.trigger("change");
    

    Remove item

    $('#mySelect option[value="option1"]').remove();
    $select2.trigger("change");
    

    Select one option

    $select2.val("option1").trigger("change");
    

    Select multiple options

    $select2.val(["option1", "option2"]).trigger("change");
    

    Remove one from selected

    If you need remove one option from already selected, you need to get selected options, remove one, and set new options to select2.

    var sel = $select2.val(); // array
    sel.splice(sel.indexOf("option1"), 1);
    $select2.val(sel).trigger("change");