Alvin Alvin - 23 days ago 6
Javascript Question

Loop through my table's specific column

html

<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>

</tbody>
</table>


Javascript

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = newRow.insertCell(0);

var otherCell = newRow.insertCell(2);

var check;
var myText = result.text;
var myTextTwo = myText.replace(/['"]+/g, '');
alert(myTextTwo);

for (var i = 0; i < tableRef.rows.length; i++) {

if (myTextTwo != tableRef.rows[i].cells[0].innerHTML) {
check = true
}
else if (myTextTwo == tableRef.rows[i].cells[0].innerHTML) {
tableRef.rows[i].cells[2].innerHTML += 1;
check = false;
break;
}
}

if (check) {
var newText = document.createTextNode(myTextTwo);
var otherText = document.createTextNode("1");
newCell.appendChild(newText);
otherCell.appendChild(otherText);
}
else {
alert("You have scanned this item before.");
}


What I have done is scanning a QR that contains a Product ID(e.g. "123") and insert the Product ID into the column called "Product ID", which I am able to do it.

However, what I am trying to do now is to, if the user scan a QR code that contains the same Product ID(e.g. "123"), my code will be able to detect the duplicate and add onto the quantity.

So what I planned to do is to loop through "Product ID" column and check if there's any duplicate. If there isn't any duplicates, the Quantity for the Product ID would be 1.

Product ID | Product Name | Quantity
123 | Hello | 1


Otherwise, duplicate exist, Quantity would be 2.

Product ID | Product Name | Quantity
123 | Hello | 2

Answer

Do you mean something like this?

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

// save the row number of the existing product
var found = false;
var myText = result.text;
var myTextTwo = myText.replace(/['"]+/g, '');

// search the table for the existing product
for (var i = 0; i < tableRef.rows.length && !found; ++i) {
  // if you found it then
  if (tableRef.rows[i].cells[0].innerHTML == myTextTwo) {
    // update the value
    tableRef.rows[i].cells[2].innerHTML += 1;

    // and say we found it
    found = true;
  }
}

// at this point, if we didn't find anything then add a new row
if (!found) {
  var newRow = tableRef.insertRow(tableRef.rows.length);
  newRow.insertCell(0).innerText = "...";
  newRow.insertCell(0).innerText = "...";
  newRow.insertCell(0).innerText = 1;
}

<table id="myList">
  <thead>
    <tr>
      <td>Product ID</td>
      <td>Product Name</td>
      <td>Quantity</td>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>