Search code examples
javascriptjquerylistlistviewsearchbar

jQuery Find a text from the list and highlight it


I have a searchbar:

<input type="search" data-cancel-btn=false 
name="search" id="searchbar" value="" placeholder="Seach"/>

and list:

temp    += '<li class="ui-li-has-multiline" id="' + id
    + '" name="' + name
    + '" status="' + status
    + '" sortId="' + sortId
    + '" img="'+ img
    + '"> <a href="#"> '
    + '<img src="' + img
    + '" alt="icon" class="ui-li-bigicon" '
    + 'style="border-radius:50px; border:2px solid dimgray; overflow:hidden ">'+ name
    + '<span class="ui-li-text-sub" style="float:left;left:5px;top:30px;">'+lastMessageText+'</span>'
    + '<span class="ui-li-text-sub2">'+lastMessageTime+'</span>';

if (status == 'online') {
    temp += '<img class="ui-li-icon-sub" src="../res/online_list.png" alt="online">';
}
temp += '</a></li>';

$("#messagesList").html(temp);

I want to realize the search by each input change in searchbar with highlighting searching text. but my function doesn't work(alert return the value of "sortId" parameter of <li>):

 $("#searchbar").on("input change", function (e) {
        var regEx;
        var content;

        content = $("#allFriendsList");
        regEx = new RegExp(".*" + $("#searchbar").val().toLowerCase());

        $(content).find("li").each(
        function () {               
            alert($(this).text());

            if ($(this).text().toLowerCase().match(regEx)) {
                $(this).show();
            } else {
                $(this).hide();
            }
            return false;
        });
        return false;
    });

Solution

  • You could use: jQuery Highlight plugin

    and in your code:

    $('li').highlight($('#searchbar').val());
    

    you should probably do this only after a minimum 3 chars or so..