Hello, I have a page with a big table full of information and I would like to add something like a search from, but what I need is that it will only highlight the text from the current page text. something like using CONTROL + F on firefox.. any way to do this? Thanks !!
You can try something like this for table: <html> <script> function search() { var search = document.getElementById('text').value; var table = document.getElementById('data'); var cells = table.getElementsByTagName('td'); for(i = 0, j = cells.length; i < j; i++) if(cells[i].innerHTML.indexOf(search) > 0) cells[i].style.backgroundColor = 'red'; else cells[i].style.backgroundColor = 'transparent'; } </script> <input type="text" id="text" onChange="javascript:search()"> <table id="data" border="1"> <tr> <td>value1</td> <td>value2</td> </tr> <tr> <td>value3</td> <td>value4</td> </tr> </table> </html> Code (markup):
And this? <html> <script> function search() { var search = new RegExp(document.getElementById('text').value, "i"); var table = document.getElementById('data'); var cells = table.getElementsByTagName('td'); for(i = 0, j = cells.length; i < j; i++) if(cells[i].innerHTML.match(search)) cells[i].style.backgroundColor = 'red'; else cells[i].style.backgroundColor = 'transparent'; } </script> <input type="text" id="text" onChange="javascript:search()"> <table id="data" border="1"> <tr> <td>value1</td> <td>value2</td> </tr> <tr> <td>value3</td> <td>value4</td> </tr> </table> </html> Code (markup):
Hi Kaimi, your code worked just perfectly, however there are two things that i would like to know if it's possible to change: 1.- If I search for nothing it will mark the whole table. http://geupload.com/images/img1.jpg 2.- When there's a match, it will only mark the TD's that have the word I've searched, is it possible to make it select the whole TR? http://geupload.com/images/img2.jpg Thanks a lot for your help!
<html> <script> function search() { var search = new RegExp(document.getElementById('text').value ? document.getElementById('text').value : '^$', 'i'); var table = document.getElementById('data'); var cells = table.getElementsByTagName('td'); var tmp = -1; for(i = 0, j = cells.length; i < j; i++) if(cells[i].innerHTML.match(search) && tmp != cells[i].parentNode.rowId) { cells[i].parentNode.style.backgroundColor = 'red'; tmp = cells[i].parentNode.rowId; } else if(tmp != cells[i].parentNode.rowId) cells[i].parentNode.style.backgroundColor = 'transparent'; else tmp = -1; } </script> <input type="text" id="text" onChange="javascript:search()"> <table id="data" border="1"> <tr> <td>value1</td> <td>value2</td> </tr> <tr> <td>value3</td> <td>value4</td> </tr> <tr> <td>value1</td> <td>value2</td> </tr> </table> Code (markup):
Hello Kaimi, it doesn't seems to be working with the last code you gave me, but the older one it does.. any idea why this could be? Thanks !