Jitender
Jitender

Reputation: 7971

show and highlight exact word match

I am creating custom filter for data. I want to show result on exact word match. for example I have following data. if we type "amit" in search input then first row should display which is working but when we type "mit" no row should be visible. fiddle

<li><strong>my name is amit</strong>, address</li>
<li><strong>my name is geeta</strong>, address</li>
<li><strong>my name is xyz</strong>, address</li>

Upvotes: 0

Views: 207

Answers (2)

renakre
renakre

Reputation: 8291

Building on top of Sridhar's solution, I built a demo https://jsfiddle.net/sumL5eas/15/, that searches also the starting words:

In my solution, first it is checked if the text starts with the search term, if so, it displayes that item. Otherwise, it search through the text with " " + searchTerm.

$('.inp').keyup(function(){

    var searchText = $(this).val();

    $('ul > li').each(function(){

        var currentLiText = $(this).text();
        var showCurrentLi = currentLiText.indexOf(searchText) == 0;
        if(!showCurrentLi)
          showCurrentLi = currentLiText.indexOf(" " + searchText) !== -1;

        $(this).toggle(showCurrentLi);

    });     
});

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20418

Try this code

$(function(){

    $('.inp').keyup(function(){

        var searchText = $(this).val();

        $('ul > li').each(function(){

            var currentLiText = $(this).text(),
                showCurrentLi = currentLiText.indexOf(searchText) !== -1;

            $(this).toggle(showCurrentLi);

        });     
    });

});

Link : http://jsfiddle.net/sumL5eas/5/

Upvotes: 1

Related Questions