Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Search Table Column for String

I am searching my Table Column for the string "None". It does this but I am unable to get the row number after. I am attempting to use the "rowIndex" attribute. Not sure why it is pulling "Not a Number" (NaN). Table is 50 rows 10 cols. I am assuming it may have to do with that I am pulling from a column instead of Row.

function F0416()                                                                   
{

var tab = document.getElementById('part1Table');
var l = tab.rows.length;
var s = '';
for ( var i = 0; i < l; i++ )
{var tr = tab.rows[i];
var cll = tr.cells[2];                                                              
s += ' ' + cll.innerText;
}

var y = (s.indexOf('None') != -1)                                                   
document.write(this.rowIndex + 1)
like image 203
JohnB Avatar asked Sep 19 '26 22:09

JohnB


2 Answers

Instead of concatenating all the values of the column into a string and searching the string, you could instead test the value of each cell in the column for the value 'None'. Then you would know the row number from the loop counter, and you could halt the loop if you find it instead of iterating over every row.

It would look more like this:

for ( var i = 0; i < l; i++ ) {
    var tr = tab.rows[i];
    var cll = tr.cells[2];                                                              
    if(cll.innerText.indexOf('None') != -1) {
        document.write(i + 1);
        break;
    }
}

You could also return the value of the row instead of outputting it.

like image 98
Surreal Dreams Avatar answered Sep 22 '26 10:09

Surreal Dreams


I would recommend using a rich javascript library like JQuery.

Then given the following HTML:

<table>
    <tr><td>Row 1- Column 1</td><td>Row 1 - Column 2</td>
    <tr><td>none</td><td>Row 2 - Column 2</td>
    <tr><td>Row 3- Column 1</td><td>Row 3 - Column 2</td>
</table>

You can use the following to get all the rows containing none:

var rows = $('table tr').filter(":contains('none')");

Have a look at this Fiddle example.

like image 22
shenku Avatar answered Sep 22 '26 10:09

shenku