Search code examples
javascriptjquerydrop-down-menujquery-select2html-select

select 2 jquery custom attribute country name with capital name


I'm trying to add a custom attribute to select 2 options, Even if I search with "data-name" the option should show up

 <select name="countries" class="vat" id="example">
        <option value="USA" data-name="Newyork" selected="selected">United States</option>
        <option value="UK"  data-name="london">Unied Kingdom</option>
        <option value="DE"  data-name="Berlin">Germany</option>
    </select>

I'm trying to approach in the search, if I type berlin, Germany should show up on the select list

<script type="text/javascript">
        $(document).ready(function() {
            $("#example").select2().find(":selected").data("name");
        });
    </script>

Please try to help me on this

Thanks


Solution

  • You can use matcher method of select2 plugin . So ,whenever user typed inside input-box you can filter options inside select-box using ..indexOf(input_value). If the value is true then option will be shown else it will get hidden.

    Demo Code :

    $(function() {
      $("select").select2({
        "width": "150px",
        matcher: function(term, text, option) {
          //get input box value 
          var input_value = $(".select2-input").val().toLowerCase();
          //get the data attribute value..
          var data_name = $(option[0]).data("name").toLowerCase();
          //if match ..show that option
          return data_name.indexOf(input_value) != -1 || option[0].textContent.toLowerCase().indexOf(input_value) != -1;
        }
      })
    
    })
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" />
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
    
    <select name="countries" class="vat" id="example">
      <option value="USA" data-name="Newyork" selected="selected">United States</option>
      <option value="UK" data-name="london">Unied Kingdom</option>
      <option value="DE" data-name="Berlin">Germany</option>
    </select>