How can i highlight the results on a search

if i am searching “america” when i am typing i want to highlight the parcial result, like

america

Kevin gave an example of how to do this using a custom matcher in #3153:

I ended up giving someone a solution to this on Stack Overflow the day before this was asked.

Part of the issue here is that 4.0.0 abstracted the results away from the actual querying of them, so it’s not as easy to implement this. With that in mind, 90% of the code below is the markMatch function from 3.5.2.

Example jsbin: http://jsbin.com/pusiqutazo/1/watch?css,js,output

JavaScript

var query = {};
var $element = $('#my-happy-select');

function markMatch (text, term) {
  // Find where the match is
  var match = text.toUpperCase().indexOf(term.toUpperCase());

  var $result = $('<span></span>');

  // If there is no match, move on
  if (match < 0) {
    return $result.text(text);
  }

  // Put in whatever text is before the match
  $result.text(text.substring(0, match));

  // Mark the match
  var $match = $('<span class="select2-rendered__match"></span>');
  $match.text(text.substring(match, match + term.length));

  // Append the matching text
  $result.append($match);

  // Put in whatever is after the match
  $result.append(text.substring(match + term.length));

  return $result;
}

$element.select2({
  templateResult: function (item) {
    // No need to template the searching text
    if (item.loading) {
      return item.text;
    }

    var term = query.term || '';
    var $result = markMatch(item.text, term);

    return $result;
  },
  language: {
    searching: function (params) {
      // Intercept the query as it is happening
      query = params;

      // Change this to be appropriate for your application
      return 'Searching…';
    }
  }
});

CSS

.select2-rendered__match {
  text-decoration: underline;
}
2 Likes

Some fix for who is using html in options:

function markMatch (text, term) {
    var regEx = new RegExp("(" + term + ")(?!([^<]+)?>)", "gi");
    var output = text.replace(regEx, "<span class='select2-rendered__match'>$1</span>");
    return output;
}

and css

.select2-rendered__match {
    background-color: #ffcc00;
}

This will prevent replacing term string inside html tags, breaking the markup.