Click here to Skip to main content
15,906,333 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am implementing the search functionality after search word is highlighted .Actually I also implement next and previous functionality .Actually when i run it search the word correctly and user go next and previous (finely). But when user search second time it highlight the first word also. Here i am implementing this functionality. http://jsfiddle.net/ravi1989/wjLmx/2/

If you check error :

First search : sd then go next . again search df. You find it highlight the first word also.

C#
function searchAndHighlight(searchTerm, selector) {
    if(searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "#realTimeContents";                             //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm,"ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if(matches!=null&&matches.length>0) {
           $('.highlighted').removeClass('highlighted');     //Remove old search highlights
                $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
           $('.match:first').addClass('highlighted');
            $('.next_h').on('click',i=1, function()
        {


            $('.match').removeClass('highlighted');
            $('.match').eq(i).addClass('highlighted');

          i=i+1;
        k=i-2;

     });
                  $('.previous_h').on('click',k=1, function()
        {

          if(matches.length>k&&k>0){
            $('.match').removeClass('highlighted');
            $('.match').eq(k).addClass('highlighted');
          k=k-1;
            i=k+2;

          }
     });




            if($('.highlighted:first').length) {             //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

$(document).on('click', '.searchButtonClickText_h', function(event) {

   $(".highlighted").removeClass("highlighted").removeClass("match");
     if(!searchAndHighlight($('.textSearchvalue_h').val())) {
            alert("No results found");
        }


});
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900