Search code examples
javascriptyui

Using YUI to read data from HTML table?


I generate an html table using YUI/JavaScript. I am now trying to go through and store the information that is generated by looking at each item in the table using a for loop.

var savedata = function(){
    var tabledata = Y.one("#generatedtable")._node;
    var jData = [];
    for (var r in tabledata.rows){
        var samplerow = {};
        samplerow.timestamp = r.cells[0].innerHTML;
        samplerow.volts = r.cells[1].innerHTML;
        samplerow.amps = r.cells[2].innerHTML;
        samplerow.kW = r.cells[3].innerHTML;
        samplerow.kWh = r.cells[4].innerHTML;
        samplerow.sessionid = r.cells[5].innerHTML;
        jData.push(samplerow);
        }
};

using Chrome developer tools I can see that Y.one("#generatedtable")._node.rows gives me an HTMLcollection of [X]. This signifies the number of rows that were created by my previous function. Row[0] is just headers and I want to skip over this row. The loop fails on the

samplerow.timestamp = r.cells[0].innerHTML;

line. How should I structure this for loop to go through rows[0] to [X] to store in my JSON Data variable?


Solution

  • var savedata = function(){
        var tabledata = Y.one("#generatedtable")._node;
        var jData = [];
        var i = 1;
        var length = tabledata.rows.length
        while (i<length){
            var samplerow = {};
            var r = tabledata.rows[i];
            samplerow.timestamp = r.cells[0].innerHTML;
            samplerow.volts = r.cells[1].innerHTML;
            samplerow.amps = r.cells[2].innerHTML;
            samplerow.kW = r.cells[3].innerHTML;
            samplerow.kWh = r.cells[4].innerHTML;
            jData.push(samplerow);
            i++;
            }
    
    alert(jData);
    };