Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search values from first column in html table using JS?

I have this table

<th>Example No.</th>
<th>Column 1</th>
<tr>
<td id="SampleId">3512376894</td>
<td>[email protected]</td>
</tr>

I have script that search the values by all columns. But all I want to do is search the values by first column only with td id. But I don't know how to do that. Please kindly, help me to do that? Thanks!

Here's the jsfiddle file

Here's the JScript:

function doSearch() {
        var searchText = document.getElementById('searchTerm').value;
        var targetTable = document.getElementById('dataTable');
        var targetTableColCount;
        for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
            var rowData = '';
            if (rowIndex == 0) {
                targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
                continue; //do not execute further code for header row.
            }
            for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
                rowData += targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
                if (rowIndex <= 1) {
                    document.getElementById('noresults').style.display = "block";
                }
            }
        }
    }
like image 731
User014019 Avatar asked Mar 19 '23 15:03

User014019


1 Answers

Use the snippet below to search within a given column for a certain term.

<!-- HTML -->
<table id="dataTable">
  <th>Example No.</th>
  <th>Column 1</th>
  <th>Column  2</th>
  <tr>
    <td>345678917</td>
    <td>Test 1</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>3512376894</td>
    <td>Test 2</td>
    <td>[email protected]</td>
  </tr>  
</table>

// JavaScript
window.onload = function(){
  var term = "3512376894";                   // term you're searching for
  var column = 0;                            // which column to search
  var pattern = new RegExp(term, 'g');       // make search more flexible 
  var table = document.getElementById('dataTable');
  var tr = table.getElementsByTagName('TR');
  for(var i = 0; i < tr.length; i++){
    var td = tr[i].getElementsByTagName('TD');
    for(var j = 0; j < td.length; j++){
      if(j == column && td[j].innerHTML == term){

      // for more flexibility use match() function and the pattern built above
      // if(j == column && td[j].innerHTML.match(pattern)){

        console.log('Found it: ' + td[j].innerHTML);
      }
    }    
  }
};

Output:

Found it: 3512376894

Working jsBin or jsFiddle or this version jsFiddle

Verions 4 | Verions 5 | Verions 6

like image 95
hex494D49 Avatar answered Apr 01 '23 07:04

hex494D49