Create search tags for Select2

0

I'm using the Select2 library. I will use it to search for help pages, however I need it to search for tags and not just for the text in Option ex:

Today:

<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>
</optgroup>

It searches only for Arizona, Colorado, Idaho

I would like something like this:

<optgroup label="Mountain Time Zone">
<option value="AZ" data-tag="Ari, City, USA">Arizona</option>
<option value="CO" data-tag="Col, City, Cores">Colorado</option>
<option value="ID">Idaho</option>
<option value="WY">Wyoming</option>
</optgroup>

Being able to search by the "data-tag" or any other form, however these tags would not need to appear in select

    
asked by anonymous 20.07.2015 / 17:23

1 answer

1

To do this, you have to hide the options , disable them with disabled a trigger in the elements when I select them as I did in this example: link

In CSS you hide the disabled elements:


<style>.select2-results__option[aria-disabled=true]{ display:none; }</style>

In the combobox you put below the options, tags as options that you want to call only as disabled:


<select multiple id="e1" class="js-example-tags form-control select2-hidden-accessible" style="width:300px">  
         <option value="01">Opção 1</option>
          <option value="01-01" disabled>tag1</option>
          <option value="01-02" disabled>tag2</option>
          <option value="01-03" disabled>tag3</option>
        <option value="02">Opção 2</option>
          <option value="02-01" disabled>tag4</option>
          <option value="02-02" disabled>tag5</option>
          <option value="02-03" disabled>tag6</option>
        <option value="03">Opção 3</option>
</select>

And in javascript you trigger:


var $element = $("#e1").select2({
    tags:true,
    placeholder: "Selecione os valores",
    tokenSeparators:[',', ' ']
});

$('#e1').on('change', function(){
    if ($(this).val() == '01'){
          $element.val(["01-01", "01-02", "01-03"]).trigger("change");
        }
     if ($(this).val() == '02'){
          $element.val(["02-01", "02-02", "02-03"]).trigger("change");
        }

});
    
22.07.2015 / 00:34