First of all, thanks in advance to all those who contribute to this post. I am trying to understand two things in the JS code below: 1) why must I check for an "undefined" element in a table row object when there is only one row, if second and third row objects can be referenced with the [x] index value... is there a simpler way to do this? 2) how do i appropriately clear field values on clone rows (in the addRow() function. What I have works, but not sure if it's the right way to do clear values).
Fiddle: https://jsfiddle.net/arperez/n6azm28k/7/
Here's the full script ("myTable" is within a FORM element named "myForm" inside the BODY tag):
function addRow() {
var tblBody = document.getElementById("myTable").tBodies[0];
var lastrow = tblBody.rows.length;
var newNode = tblBody.rows[0].cloneNode(true);
tblBody.appendChild(newNode);
//Clear copied values from cloned row.
document.myForm.txtQty[lastrow].value = ""; //This works, but is this the right way to clear the textbox value of the cloned row?
}
function calcTotals() {
var qty = 0;
var totalqty = 0;
var rows = document.getElementById("myTable").tBodies[0].rows.length - 1;
for (i=0; i<=rows; i ) {
var element = document.myForm.txtQty[i];
if (element === undefined) { //If I don't do this check I get an error when there is only one row existing in the table and I try referencing it with [0]. Not sure why?
qty = document.myForm.txtQty.value; //This works, but why does txtQty[0] not work? Is this the right way to refer to the first element/row?
} else {
qty = document.myForm.txtQty[i].value;
}
totalqty = totalqty Number(qty);
}
//Display total quantities calculated
alert("Total = " totalqty);
}
<table id="myTable">
<thead>
<th>Quantity</th>
</thead>
<tbody>
<tr>
<td><input type="number" id="txtQty" name="txtQty"></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>
CodePudding user response:
In the beginning, you have only 1 element which name is "txtQty", so the document.myForm.txtQty is not an array.
Your solution is ok.
Here is my implementation:
function addRow() {
var tblBody = document.getElementById("myTable").tBodies[0];
var lastrow = tblBody.rows.length;
var newRow = tblBody.insertRow();
var newCell = newRow.insertCell();
newCell.innerHTML = '<input type="number" name="txtQty[]">';
}
function calcTotals() {
var totalqty = 0;
var qty = 0;
var totalqty = 0;
var txtQtys = document.getElementsByName('txtQty[]');
for (i=0;i<txtQtys.length;i ){
totalqty =Number(txtQtys[i].value) ;
}
alert("Total = " totalqty);
}
<body>
<form name="myForm">
<table id="myTable">
<thead>
<th>Quantity</th>
</thead>
<tbody>
<tr>
<td><input type="number" name="txtQty[]"></td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>
</form>
</body>