Reputation: 129
<tr>
<td><input type="text" name="description" required /></td>
<td><input type="text" name="quantity" id="quantity" onkeyup="sum();" required /></td>
<td><input type="text" name="price" id="price" onkeyup="sum();" required /></td>
<td><input type="text" name="lineTotal" id="lineTotal" readonly /></td>
<td><input type="button" onclick="addLine();" value="+" /></td>
</tr>
Below is my javascript code
<script type="text/javascript">
function addLine() {
var tabLines = document.getElementById("tabLines");
var tabLinesRow = tabLines.insertRow(tabLines.rows.length-1);
var col1html = "<input type='text' name='description' />";
var col2html = "<input type='text' name='quantity' id='quantity' onkeyup='sum();' />";
var col3html = "<input type='text' name='price' id='price' onkeyup='sum();' />";
var col4html = "<input type='text' name='lineTotal' id='lineTotal' readonly />";
var col5html = "<input type='button' onclick='removeLine(this);' value='-'>";
var col1 = tabLinesRow.insertCell(0); col1.innerHTML=col1html;
var col2 = tabLinesRow.insertCell(1); col2.innerHTML=col2html;
var col3 = tabLinesRow.insertCell(2); col3.innerHTML=col3html;
var col4 = tabLinesRow.insertCell(3); col4.innerHTML=col4html;
var col5 = tabLinesRow.insertCell(4); col5.innerHTML=col5html;
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function sum() {
var q = document.getElementById('quantity').value;
var p = document.getElementById('price').value;
var result = parseInt(q) * parseInt(p);
if(q=="" || p==""){
document.getElementById('lineTotal').value = 0;
}
if (!isNaN(result)) {
document.getElementById('lineTotal').value = result;
}
}
</script>
I am trying to do some calculations here. When i calculate the default single row, it does calculate, when i press on add button and i do some calculations in the second row it works, but when i add more rows it does not calculate. I don't know how to solve it. Please help as i a newbie in javascript
Upvotes: 0
Views: 356
Reputation: 2225
That right there is your problem. The id attribute in an HTML element should be unique in the entire page. However, you could try to add an index as a suffix for each repeated element in your rows, like "quantity1", "price1", etc.
I also suggest trying out the developer tools within your browser, specially the console and the debugger. There you can run your javascript code step by step (debugger) or on demand (console) to check where do you have an error.
Upvotes: 1
Reputation: 12940
ID's are something that has to be unique. If you need to refer to elements that are the same, use class
instead.
Upvotes: 1
Reputation: 723
Looks like your problem is that you are duplicating ID's
Try adding an index for your ID's for each row added
Upvotes: 2