user1287923
user1287923

Reputation: 31

jQuery Character search

I want change the background color of limited character in a string

I have text box and string, I want to change the background-color of the string from the text box
Using Jquery eg:

When I enter the text 'char' in the text box i need to change all 'char' and 'CHAR' text listed ul

<ul class="brows_all_cat"> 

<li><a> My sample character1  </a></li>
<li><a> My sample CHARACTER2  </a></li>
<li><a> My sample character3  </a></li>
<li><a> My sample character4  </a></li>
</ul>

Upvotes: 2

Views: 764

Answers (2)

otakustay
otakustay

Reputation: 12395

  1. Create a variable to store entered phrase:

    var word = '';

  2. Write an event handler

    $(document).on('keypress', highlight);

  3. Now implement hightlight function:

    function highlight(event) {
        // ...
    }
    
    1. Add pressed key to phrase:

      word += String.fromCharCode(event.which);
      
    2. Extract innerText from all <a> elements, then add hightlights, by wrapping phrase with an <span> element

      $('li>a').each(function() {
          var element = $(this);
          var text = element.text();
          text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>');
          element.html(text);
      });
      
  4. Add a style to .highlight selector:

    <style>
        span.highlight {
            color: red;
        }
    </style>
    

By combining all code, it should be like below:

var word = '';

function highlight(event) {
    word += String.fromCharCode(event.which);
    $('li>a').each(function() {
        var element = $(this);
        var text = element.text();
        text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>');
        element.html(text);
    });
}

$(document).on('keypress', 'highlight');

There is still one problem left, when would be the phrase be cleared, after a certain time that document doesn't receive any keypress event, or is there any other strategy?

Upvotes: 3

Joseph
Joseph

Reputation: 119847

i think you mean the .contains() selector, especially making it case-INsensitive

//make :contains() case insensitive
jQuery.expr[':'].Contains = function(a, i, m) { 
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
};

//then 

var elementsThatHaveText = $('.brows_all_cat a:contains("'+text_you_need+'")');

Upvotes: 1

Related Questions