user3106578
user3106578

Reputation: 177

How to highlight searchtext records in javascript?

Name Role

applicationame          role                     id
application1           appadministrator      1490
application            developer             1498
application2            tester               1460

I need the result like if entered 'app' as searchtext need to highlight all rows ,because all rows are having app.if entereted 'application' as searchtext then need to highlight 2nd row only. because exact macth.like that i need to check all columns i.e aplication,role etc. no need of hide the unmacthed rows.need to highlight matching only if not macth just display as it is.

if user entered '14' as searchtext need to highlight all rows.if he entered 1490 need to highlight 1strow and display remaining rows as it is.please help me to achieve this.

My fidler: http://jsfiddle.net/kUxNj/4/

Please modify my fidler according this.

Upvotes: 0

Views: 93

Answers (2)

Canis
Canis

Reputation: 4400

Using the match() method instead of the equality check:

if ($(this).find('td:first-child').text().toUpperCase().match( text.toUpperCase()) ||
    $(this).find("td:eq(1)").text().toUpperCase().match( text.toUpperCase())) 
{
    $(this).children('td').addClass('result');
}

I also removed the hide() and show() calls as they are redundant to highlighting rows like you ask.

Updated fiddle: http://jsfiddle.net/kUxNj/9/

Upvotes: 1

ProgramFOX
ProgramFOX

Reputation: 6390

You should replace this:

if ($(this).find('td:first-child').text().toUpperCase() === text.toUpperCase() ||
                    $(this).find("td:eq(1)").text().toUpperCase() === text.toUpperCase()
                   )

With this:

if ($(this).find('td:first-child').text().toUpperCase().indexOf(text.toUpperCase()) != -1 ||
                    $(this).find("td:eq(1)").text().toUpperCase().indexOf(text.toUpperCase()) != -1
                   )

How it works: your code looks whether the given text is equal to one of the rows, but my code checks whether one of the rows contains the given text, using the indexOf() method.

And to avoid hiding of non-matching elements, remove the following code:

if(grid.find('td.result').length >0){
                grid.find('td').not('.result').parent('tr').hide();
            }

Updated fiddle: http://jsfiddle.net/kUxNj/7/

Upvotes: 2

Related Questions