Search for the option title using select2

Asked

Viewed 605 times

4

I have a select element and I need to search the items (options) not only for the text, but also for the title (or any other attribute), I have already been able to put the title to appear when expanding the element, but I can’t do a search in it.

I’m using the plugin Select2 in version 3.5.2

<select id="estado" class="form-control">
    <option value="SP" title="São Paulo">SP</option>    
    <option value="RJ" title="Rio de Janeiro">RJ</option>
    <option value="SC" title="Santa Catarina">SC</option>    
</select>

$("#estado").select2({

    formatResult : function(item) {
        var markup = '<div class="row">' +
             '<div class="col-lg-12">' + item.text + '</div>' +
             '</div>' +
             '<div class="row">' +
             '<div class="col-lg-12 text-muted">' + item.element[0].title + '</div>' +
             '</div>';

          return markup;
    }
});

Follow the example running on jsfiddle

1 answer

1


Customize the matcher from Select2. Using your example:

$("#estado").select2({

  formatResult : function(item) {
            var markup = '<div class="row">' +
                 '<div class="col-lg-12">' + item.text + '</div>' +
                 '</div>' +
                 '<div class="row">' +
                 '<div class="col-lg-12 text-muted">' + item.element[0].title + '</div>' +
                 '</div>';

              return markup;
  },
  matcher: function(term, text, opt) {
       return text.toUpperCase().indexOf(term.toUpperCase())>=0
           || opt.attr("title").toUpperCase().indexOf(term.toUpperCase())>=0;
  }
});

Fiddle: http://jsfiddle.net/22cuj35L/1/

Browser other questions tagged

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