Search code examples
jqueryhighlighting

Highlight letters typed in the input box


I would like to highlight the text typed in the inbox , and when its found in a table column, td, then it should highlight it, otherwise remove the highlight from it.

Here is a fiddle with my code: http://jsfiddle.net/rFGWZ/6/ , try to type 21 in the text input, so 2 rows will be only visible, and I would like to select 21 in each td that is visible in the case and this is the text that was typed in the input.

I've tried many highlight scripts posted in the web, but none of them seems to work because I can not really localize the element, as this is the live query search...


Solution

  • You have to create a span containing only highlighted characters. I suggest you this code:

        $("table tr").each(function(index) {
            if (index !== 0) {
    
                $row = $(this);
                var firstCell = $row.children("td:first");
    
                var id = $row.children("td:first").text();
                if (id.indexOf(value) !== 0) {
                    $row.children("td:first").text(id);
                    $row.hide();
                }
                else {
                    firstCell.html($("").addClass("highlight").text(id.slice(0, value.length)));
                    firstCell.append(id.slice(value.length, id.length));
                    $row.show();
                }
            }
        });
    

    Don't forget to customize .highlight rule in your CSS.

    See it live!