user3047780
user3047780

Reputation: 33

How to get count value increamented within loop

http://jsfiddle.net/KKH9a/16/

Tried using console using table1.rows[0].cells[1].innerHTML => "Numbers" Tried even this code table1.rows[0].cells[1].innerHTML!=null => true

But if I try this code below:

HTML:

<table id="table1">
<tr>
    <td>Value</td>
    <td></td>
</tr>
<tr>
    <td>Value</td>
    <td>Value</td>
</tr>
<table>

Javascript:

for (var i = 0; i < table1.rows.length; i++) {
    for (var j = 0; j < table1.rows[i].cells[j].innerHTML; j++) {
        if (table1.rows[i].cells[j].innerHTML != null) {
            var count = 0;
            count = count + 1;
            alert(count);
        }
    }
}

Upvotes: 1

Views: 3904

Answers (4)

Hayk Mantashyan
Hayk Mantashyan

Reputation: 328

Calculate count of cells using JQuery after document is ready

$(document).ready(function() {
    var count = 0;
    $('#table1 td').each(function() {
        if($(this).html() != "") {
            count++;
        }
    });
    alert(count);
});

Updated Demo: http://jsfiddle.net/KKH9a/27/

Upvotes: 0

Sebastien C.
Sebastien C.

Reputation: 4833

First, you shouldn't use innerHTML to check if there is something in a node. Just count the number of childs instead :

if (table1.rows[i].cells[j].childNodes.length > 0) {

Secondly, if you declare count inside the loops, it will be resetted at each iteration.

Thirldy, I don't understand what you're trying to do with j < table1.rows[i].cells[j].innerHTML. And innerHTML is a String, not a number. You should use parseInt on it.

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

  1. table1 isn't defined. You need to use document.getElementById to get a reference to your table element.
  2. On line 2 you're specifying j < table1.rows[i].cells[j].innerHTML. This doesn't make any sense and should be changed to j < table1.rows[i].cells.length.
  3. You need to move your count variable completely outside your loop, otherwise it will always be equal to 1.

Change your code to this:

var table1 = document.getElementById('table1');
var count=0;

for(var i=0;i<table1.rows.length;i++)
{
    for(var j=0;j<table1.rows[i].cells.length;j++)
    {
        if(table1.rows[i].cells[j].innerHTML!=null)
        {
            count++;
            alert(count);
        }
    }
}

Working JSFiddle demo.

Upvotes: 3

slim
slim

Reputation: 41223

Work on understanding how Javascript interacts with the HTML DOM.

At present your code refers to "table1", but this has nothing to do with the HTML element with the id "table1".

Introductory Javascript tutorials will explain how to get DOM elements into variables. To make things easier, you could use JQuery or something similar.

Once you're past that, you can start looking at the errors in your for loop logic (which other answers have already addressed).

Upvotes: 0

Related Questions