Create search tags for Select2

Asked

Viewed 339 times

0

I’m using the library Select2. I’ll use it to search for help pages, but I need it to search for tags and not just for 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>

He only searches Arizona, Colorado, Idaho

I’d like something like:

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

You can search by "data-tag" or any other way, but these tags would not need to appear in select

  • 1

    Have you looked at this? https://harvesthq.github.io/chosen/

  • Thank you, but this unfortunately does not also have the option to search in some field and show another

1 answer

1


To do this, you have to hide the options, disable them with disabled and then give a Trigger in the elements when selecting them as I did in this example: http://jsfiddle.net/jEADR/1842/

In CSS you hide the deactivated elements:


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

In the combobox you put below the options, the tags as options 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 do 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");
        }

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.