espresso_coffee
espresso_coffee

Reputation: 6110

How to iterate through table tr and get the value for first td? JavaScript

I have the function where I want to get the value for first td in each table row. While looping I want to compare each of these values with the date value that user picked. After comparing the dates I need to get the position where that value should be placed in the table. Here is example of my code:

HTML Table:

<table id="tblBody_DBA">
    <tbody>
        <tr id="Att_5258717">
            <td>03/28/2017</td>
            <td></td>
        </tr>
        <tr id="Att_5258339">
            <td>03/25/2017</td>
            <td>03/26/2017</td>
        </tr>                       
        <tr id="Att_5258337">
            <td>03/22/2017</td>
            <td>03/24/2017</td>
        </tr>
        <tr id="Att_5258332">
            <td>03/16/2017</td>
            <td>03/21/2017</td>
        </tr>
        <tr id="Att_5258331">
            <td>03/10/2017</td>
            <td>03/15/2017</td>
        </tr>
    </tbody>
</table>

 function sortRow(distType, rowId){
        var newVal = document.getElementById("newDate").value; //this is new value that I have to compare against existing values and return position in the table.
        var tblID = document.getElementById("parentTable").value;
        var table = window.parent.document.getElementById("tblBody_"+tblID);
        var arrayDates = [];

        for(var i=0; table.rows.length; i++){
            //Here I'm getting JavaScript error: TypeError: table.rows[i] is undefined
            alert(table.rows[i].cells[0].innerHTML);
        }

    }

I'm getting value for each table cell in alert box but on the end error shows in my debugger. If anyone can help please let me know. I'm not able to use JQuery, plain JavaScript is the only way to et this done in my case.

Upvotes: 1

Views: 16744

Answers (6)

vol7ron
vol7ron

Reputation: 42099

Forgot to paste this snippet, which might help. Until you answer the questions on the comment, there's no way to determine the best approach.

Note: The following code uses some ES6 syntax, which may not be available in IE as @Brian has pointed out. For that reason, Babel.js or a suitable Polyfill is encouraged.


The idea is to grab the first-child cell of each row and iterate over them. Using map you can return an array, which can then be sorted, or queried using indexOf.

By returning the element as the first item of the array, you can use [0].parentNode to retrieve the TR, or [0].parentNode.id to get it's ID.

"use strict";
let newVal = document.getElementById('newDate').value;
console.log('newVal:', new Date(newVal));

let tbl = document.getElementById('tblBody_DBA');
var col_values = [...tbl.querySelectorAll('tr > td:first-child')].map(el => {
  return [el, el.textContent, +new Date(el.textContent)];
}).sort((a,b) => a[2] > b[2] ? -1 : 1);

console.log(col_values);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<p>I have the function where I want to get the value for first td in each table row. While looping I want to compare each of these values with the date value that user picked. After comparing the dates I need to get the position where that value should be
  placed in the table. Here is example of my code:</p>

<p>HTML Table:</p>
<input id="newDate" value='3/24/2017' type="hidden" />
<table id="tblBody_DBA" class="table table-striped">
  <tbody>
    <tr id="Att_5258717">
      <td>03/28/2017</td>
      <td></td>
    </tr>
    <tr id="Att_5258339">
      <td>03/25/2017</td>
      <td>03/26/2017</td>
    </tr>
    <tr id="Att_5258337">
      <td>03/22/2017</td>
      <td>03/24/2017</td>
    </tr>
    <tr id="Att_5258332">
      <td>03/16/2017</td>
      <td>03/21/2017</td>
    </tr>
    <tr id="Att_5258331">
      <td>03/10/2017</td>
      <td>03/15/2017</td>
    </tr>
  </tbody>
</table>
<p>
  I'm getting value for each table cell in alert box but on the end error shows in my debugger. If anyone can help please let me know. I'm not able to use JQuery, plain JavaScript is the only way to et this done in my case.</p>

Upvotes: 0

bcr
bcr

Reputation: 3811

You can just grab the first td from each tr specifically:

var table = document.getElementById('tblBody_DBA');
var targetTDs = table.querySelectorAll('tr > td:first-child');


for (var i = 0; i < targetTDs.length; i++) {
    var td = targetTDs[i];
    console.log(td.innerHTML);
}

Upvotes: 5

trincot
trincot

Reputation: 350212

The main issue is in the for loop's end condition. You did not provide a comparison with i and so it was continuing beyond the last row of the table, producing the error you got.

To find the row for which the input date falls between the dates in the first and second column, you'll need to convert those values to dates and then do a comparison:

// Parse text as date and convert to an absolute day number 
newVal = Math.floor(Date.parse(newVal) / 24*60*60*1000);
for(var i=0; i < table.rows.length; i++){
    // Do the same conversion for the table texts
    var start = Math.floor(Date.parse(table.rows[i].cells[0].textContent) / 24*60*60*1000);
    var end = Math.floor(Date.parse(table.rows[i].cells[1].textContent) / 24*60*60*1000);
    // Make the comparison
    if (start <= newVal && (newVal <= end || isNaN(end))) {
        return i; // the row where the range for that value was found
    }
}

Upvotes: 1

Osama
Osama

Reputation: 3040

<table id="tblBody_DBA">
    <tbody>
        <tr id="Att_5258717">
            <td>03/28/2017</td>
            <td></td>
        </tr>
        <tr id="Att_5258339">
            <td>03/25/2017</td>
            <td>03/26/2017</td>
        </tr>                       
        <tr id="Att_5258337">
            <td>03/22/2017</td>
            <td>03/24/2017</td>
        </tr>
        <tr id="Att_5258332">
            <td>03/16/2017</td>
            <td>03/21/2017</td>
        </tr>
        <tr id="Att_5258331">
            <td>03/10/2017</td>
            <td>03/15/2017</td>
        </tr>
    </tbody>
</table>
<script>
 function sortRow(distType){
        var table = document.getElementById(distType); //this is new value that I have to compare against existing values and return position in the table.
		for (var i = 0; i < table.rows.length; i++) {
   var firstCol = table.rows[i].cells[0]; //first column
    console.log(firstCol.innerHTML);// or anything you want to do with first col
}
    }
	sortRow("tblBody_DBA");
	
	</script>​

Upvotes: 1

Nishesh Pratap Singh
Nishesh Pratap Singh

Reputation: 2181

Possible reasons for error could be :

  1. document.getElementById("parentTable").value will be returning a value which will not map to any table id when using in window.parent.document.getElementById("tblBody_"+tblID);
  2. There are no rows in the table which has been returned by window.parent.document.getElementById("tblBody_"+tblID);
  3. Also you havn't provided terminating condition in your for loop, which should be like : for(var i=0; i < table.rows.length; i++)

One more thing why you are using window.parent when getting the table. If your table and rest of the content are in same page then you can get table by simply calling document.getElementById("tblBody_"+tblID);. If you creating multi frame page then this will be required but this will get the table from the parent window of window in which you have function sortRow defined.

Upvotes: 0

JJJ
JJJ

Reputation: 3332

First you get all of the tr elements using var allTr = document.querySelectorAll ('tr')

Then you loop through them and get the text from the first td

for (var i = 0; i  < allTr.length; i++) {
  allTr [i].firstChild.innerHTML;
}

Upvotes: 2

Related Questions