Search code examples
javascriptjqueryhtmlcssjquery-tokeninput

How to make matching chars bold+red when using jQuery Tokeninput


I am using http://loopj.com/jquery-tokeninput/demo.html#formatting

I would like to make the matching chars also red, but cannot locate the piece of CSS or Javascript they have.

enter image description here

Their project is on GitHub.


Solution

  • Using chrome developer tools I found out that jquery-tokeninput is formatting search results like the following:

    <ul style="display: block; overflow: hidden;">
        <li class="token-input-dropdown-item2-facebook">Trad<b>in</b>g Spouses</li>
        <li class="token-input-dropdown-item-facebook">T<b>in</b> Man</li>
    </ul>
    

    So it is not using a css class to highlight the matching chars, it is doing it manually putting those chars inside a <b> tag. After a quick search in the javascript source file I was able to find this function:

    // Highlight the query part of the search term
    function highlight_term(value, term) {
        return value.replace(
          new RegExp(
            "(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)",
            "gi"
          ), function(match, p1) {
            return "<b>" + escapeHTML(p1) + "</b>";
          }
        );
    }
    

    Hence, I guess it is only a matter of modifying it to be able to customize the matching chars style. For instance, you could change the returning string to:

    return '<b class="match">' + escapeHTML(p1) + '</b>';
    

    And apply your styles to the b.match css class.