hannacreed
hannacreed

Reputation: 649

JavaScript Restart Counter

I am probably overthinking the question, but how do I restart a counter? Also, as you will see in my code, the counter is supposed to match but doesn't. I want the cell to have a shared value of the row that it is in, for example the first rows cells should have the ID: cell 0.0, cell 0.1, but rather it has skipped one where the first number is one row ahead.

var rowCount = 0;
var cellCount = 0;

function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
    row = table.insertRow(table.rows.length); // append table row
  row.setAttribute('id', style);
  var i;
  row.id = 'row' + rowCount;
  rowCount++
  console.log(rowCount, cellCount);
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
    cellCount++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode('_'); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('id', style); // set DIV class attribute
  div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}
table {
  text-align: center;
}
td {
  width: 100px;
}
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

<div class="custScroll">
  <table id="custListTop" contenteditable="false">
    <tr>
      <td style="border-top-left-radius: 5px;">Customers</td>
      <td style="border-top-right-radius: 5px;">Main Location</td>
    </tr>
  </table>
  <table id="custList" contenteditable="true">
    <tr>
      <td>Someone</td>
      <td>something</td>
    </tr>
  </table>
</div>

Upvotes: 0

Views: 531

Answers (1)

ShadowCommander
ShadowCommander

Reputation: 181

I'm not sure this is what you want, but if you put rowCount++ after the for loop it starts off the first element at 0 then increments from there.

If you want the cells to start over then change createCell to use i instead of cellCount:

createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);

Upvotes: 1

Related Questions