0

I'm trying to implement a search for a table, I found an answer on the web and I tried it out, it works fine!

now I want to highlight (change text colour: text colour class = blue-text) that search keyword found in a table cell, I searched for this answer but I didn't find anything helpful!

my HTML is

<table class="stdtable">
  <tr>
    <td id="stdname">Name</td>
    <td id="stdreg">Reg. No.</td>
    <td id="stdparent">Parent</td>
    <td id="stdgrp">Group</td>
    <td id="action">Action</td>
  </tr>
</table>

and Jquery is

$("#filter").on("keyup", function() {
    var searchKey = $(this).val().toLowerCase();
    $(".stdtable tr #stdname").each( function() {
        var searchStr = $(this).text().toLowerCase();
        if (searchStr.indexOf(searchKey)!=-1) {
            $(this).parent().show();
        }
        else {
            $(this).parent().hide();
        }
    });
});

how can I highlight the searched text? if I search N the text N in Name should change the colour

and if I clear the search field I need to clear colour of the text also

rakcode
  • 2,256
  • 4
  • 19
  • 44

1 Answers1

2

I don't know the setup you have, but I would make a class "highlighted" and give this class the property: color: blue; or whatever any other css properties you want for the special results. then

$("#stdname").addClass("highlighted");

and

$("#stdname").removeClass("highlighted");

when you remove the search field

Edit: Leaving the above for someone that wants all the text.

You could take

var s = $(this).val();
var txt = $("#stdname").val().replace(s, '<span style="color: blue">' + s +  '</span>');
$("#stdname").val(txt);

please note, you are going to end up with strange behavior if you don't strip the span statement from $("#stdname").val() every time a key is up

Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27
  • not for whole string! only those text which I'm searching – rakcode Apr 07 '17 at 21:50
  • I fixed it. Try something similar to that and it should be able to change the color. for clearing you'd have to remove the span statement and replace it with the string between the `">"` spans. – Matthew Ciaramitaro Apr 07 '17 at 22:02