0

I am new into JS and I would like to be able to highlight search results in the accordion. For now the code works well for searching

I have tried to use RegExp but I didn't succeed.

(function() {
  var searchTerm, panelContainerId;

  // Create a new contains that is case insensitive
  jQuery.expr[':'].containsCaseInsensitive = function(n, i, m) {
    return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
  };

  jQuery('#accordion_search_bar').on('change keyup paste click', function() {
    searchTerm = jQuery(this).val();

    if (searchTerm.length >= 3) {
      jQuery('#accordion > .panel').each(function() {
        panelContainerId = '#' + jQuery(this).attr('id');
        jQuery(panelContainerId + ':not(:containsCaseInsensitive(' + searchTerm + '))').hide();
        jQuery(panelContainerId + ':containsCaseInsensitive(' + searchTerm + ')').show().find(".panel-collapse").collapse("show");
      });
    } else {
      jQuery(".panel-group > div").show();
      jQuery(".panel-group > div").find(".panel-collapse").collapse("hide");
    }
  });
}());
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

0

I don't think it's possible to do it without changing the markup.

If you're ok with that though you can replace the searched for text with a coloured <span> element. Give it a class so you can remove it when needed too.

Colouring it has been answered here

I'd amend it so you can remove the span when you want to refresh the search by adding a class to the span:

function color_word(text_id, word, color) {
    words = $('#' + text_id).text().split(' ');
    words = words.map(function(item) { return item == word ? "<span class='highlight' style='color: " + color + "'>" + word + '</span>' : item });
    new_words = words.join(' ');
    $('#' + text_id).html(new_words);
}

So to remove it we could do something like:

function removeHighlight(container)
{
    let highlight = $(container).find('.highlight').first();

    const markupToReplace = $(highlight).get(0).outerHTML;
    const highlightedText = $(highlight).text();

    $(container).html($(container).html().replace(markupToReplace, highlightedText));
}
Sean T
  • 2,414
  • 2
  • 17
  • 23