How to search on data attribute in select 2?

Issue

I want to search on value and data-test attribute.
in select2

<option value="Test 1" data-test="user-1">Test 1</option>
<option value="Test 2" data-test="user-2">Test 2</option>
<option value="Test 3" data-test="user-3">Test 3</option>

Solution

You can read more document for search in select2 : example same as with data :

$('.test-search').select2({
  matcher: function (params, data) {
    // If there are no search terms, return all of the data
    if ($.trim(params.term) === '') {
      return data;
    }

    // Do not display the item if there is no 'text' property
    if (typeof data.text === 'undefined') {
      return null;
    }

    // `params.term` should be the term that is used for searching
    // `data.text` is the text that is displayed for the data object
    if (data.element.dataset.test.indexOf(params.term) > -1) {
      var modifiedData = $.extend({}, data, true);
      modifiedData.text += ' (matched)';

      // You can return modified objects from here
      // This includes matching the `children` how you want in nested data sets
      return modifiedData;
    }

    // Return `null` if the term should not be displayed
    return null;
  }
});
.test-search{
  width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<select class="test-search">
<option value="Test 1" data-test="user-1">Test 1</option>
<option value="Test 2" data-test="user-2">Test 2</option>
<option value="Test 3" data-test="user-3">Test 3</option>
<option value="Test 4" data-test="employee-3">Test 4</option>
</select>

Answered By – Xupitan

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.