Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Posts
    184
    Thanks
    140
    Thanked 0 Times in 0 Posts

    Highlighting the characters that match the search, as opposed to just changing class

    Hello,

    The following javascript code works to find the match, and to change its classname to "selected" once found, however, I was thinking that it would be more functional if, the code highlighted (changed only the background of the match) as opposed to the entire line.

    How can my javascript coding be modified such that I would be able to accomplish this?

    I am jQuery friendly.

    Code:
    $("#refdocs").keyup(function(){
    
        var search = $(this).val();
        
    	$("#refdocs_list li").each(function(){
    		
    		var val = $(this).text();
            
            if (val.toLowerCase().indexOf(search) >= 0 && search.length) {
            	//$(this).addClass("selected");
            	
            	
            }
            else {
            
            	$(this).removeClass("selected");      
            }
    
        });
    });
    Here is a fiddle:
    Fiddle

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,298
    Thanks
    10
    Thanked 584 Times in 565 Posts
    Edit fiddle - JSFiddle

    replace

    Code:
         //$(this).addClass("selected");
    with
    Code:
        $(this).html(val.replace(RegExp("("+search.replace(/[\-$*{}()]/g,"\\$1")+")","ig"), "<mark>$1</mark>" ));
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • Users who have thanked rnd me for this post:

    jason_kelly (06-10-2014)

  • #3
    Regular Coder
    Join Date
    Sep 2011
    Posts
    184
    Thanks
    140
    Thanked 0 Times in 0 Posts
    Thanks so much Rnd Me!

    Worked like a charm...your crazy full of awesome sauce

    Cheers and have a great day mate.

    Jay


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •