I wrote below the javascript which will allow user to add and delete the row and calculate the weighting. The addition and deletion are working fine but I believe I am unable to do sum of weighting. Can you please advise ?
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.class = "wtotal1";
cell4.appendChild(element4);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].textContent)) )
tweight1 += parseFloat(cusid_ele[i].textContent);
}
document.getElementById('tweight1').value=tweight1;
}
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>
Two things:
1.- Replaces the attribute
element4.class = "wtotal1"; By element4.className = "wtotal1";
2 replaces the cusid_ele[i].textContent attribute with cusid_ele[i].value
The complet code
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.className = "wtotal1";
cell4.appendChild(element4);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].value)) )
tweight1 += parseFloat(cusid_ele[i].value);
}
document.getElementById('tweight1').value=tweight1;
}
</script>
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<button onclick="addRow('dataTable1')">Add Row</button><button
onclick="deleteRow('dataTable1')">Delete Row</button>
<br>
<br>
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>
Related
HTML table
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chk" id ="chk" size="6"/></td>
<td><input type="text" name="txtRow1" id="txtRow1" size="8"/></td>
<td><input type="text" name="txtRow2" id="txtRow2" size="8"/></td>
<td><input type="text" name="txtRow3" id="txtRow3" size="8"/></td>
<td><input type="text" name="txtRow4" id="txtRow4" size="8"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
</tr>
</table>
After entering data into HTML table, I want to get that data to javascript so that I could save it in the database. The HTML table contains multiple rows and four columns. User can add rows if they want to add column to enter data. I want to get all the column data to the javascript. How do I do that..Kindly help me
My HTML Code:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtbox[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
/*alert(e);*/
}
}
My javascript code to add and delete table rows:
Now after table columns are filled, i want to get that data to javascript.I tried to do like below. But it is not working.I am getting null values.I am not getting the actual values.
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++)
{
var Name = $("dataTable").find("tr").eq(i).find("td").eq(0).text();
var Designation = $("dataTable").find("tr").eq(i).find("td").eq(1).text();
var PAN = $("dataTable").find("tr").eq(i).find("td").eq(2).text();
var Address = $("dataTable").find("tr").eq(i).find("td").eq(3).text();
}
Kindly let me know what am I doing wrong and what should I do.
Thank You!
The data of an HTML table can be stored in a JS array, it's easier than putting the data into variables (which are storing the last row only).
var rows = table.rows,
len = rows.length,
data = [],
cells;
for (var n = 1; n < len; n++) {
cells = rows[n].cells;
data.push([
cells[0].firstElementChild.checked,
cells[1].firstElementChild.value,
cells[2].firstElementChild.value,
cells[3].firstElementChild.value,
cells[4].firstElementChild.value
]);
}
Now it's easy to read the values from data array when needed.
You are on the right way, but pay attention to some details:
In your solution you select the 'td' not the input inside it.
If you use an input you cannot get the innterText by calling .text() instead you want to use the .val() method to receive the
value
Name your inputs consistently. In your first row you name them "txtRow1"-"textRow4" ... but when you add new rows you name them
"txtbox[]": First of all i think you mean txtCol not txtRow ... just think about it. Second you if you want to group your inputs by column then append the "[]" brackets to the names that belong together like so "txtCol1[]" - "txtCol4[]"
I have put it all together for you:
function addRowTable(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 10) {
alert("Maximum 10 rows allowed");
return false;
}
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
element1.size = 8;
/*var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;*/
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtCol1[]";
cell2.appendChild(element2);
element2.size = 8;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtCol2[]";
cell3.appendChild(element3);
element3.size = 8;
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtCol3[]";
cell4.appendChild(element4);
element4.size = 8;
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtCol4[]";
cell5.appendChild(element5);
element5.size = 8;
}
function deleteRowTable(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
/*alert(e);*/
}
}
function readData(tableID){
var rowCount = $(tableID + ' tr').length;
var results = [];
for (var i = 1; i < rowCount; i++)
{
results.push({
Name: $(tableID).find('tr').eq(i).find('[name="txtCol1[]"]').val(),
Designation: $(tableID).find('tr').eq(i).find('[name="txtCol2[]"]').val(),
PAN: $(tableID).find('tr').eq(i).find('[name="txtCol3[]"]').val(),
Address: $(tableID).find('tr').eq(i).find('[name="txtCol4[]"]').val(),
});
}
console.log(results);
return results;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="1px" style="width:355px; BORDER-COLLAPSE:collapse">
<tr>
<td id="0" align="center"></td>
<td id="1" align="center">Name</td>
<td id="2" align="center">Designation</td>
<td id="3" align="center">PAN</td>
<td id="4" align="center">Address</td>
</tr>
<tr>
<td><input type="checkbox" name="chkbox[]" id="chk" size="6" /></td>
<td><input type="text" name="txtCol1[]" id="txtCol1" size="8" /></td>
<td><input type="text" name="txtCol2[]" id="txtCol2" size="8" /></td>
<td><input type="text" name="txtCol3[]" id="txtCol3" size="8" /></td>
<td><input type="text" name="txtCol4[]" id="txtCol4" size="8" /></td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRowTable('dataTable')" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRowTable('dataTable')" /></td>
<td><input type="button" value="Read Data" onclick="readData('#dataTable')" /></td>
</tr>
</table>
I want to add new row, and remove previously added row with an onclick event.
I write code for it but this code only insert rows not delete previous one.
js
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
html
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<table id="dataTable" border="1">
<tr>
</tr>
</table>
Use deleteRow().. and you might just be able to do it.
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount) {
table.deleteRow(-1);
}
...
}
I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>
Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.
var i = 0;
var a = 3;
function addNewAnswer(tableID) {
var table = document.getElementById(tableID);
if(i < 10)
{
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + String.fromCharCode(67+i) + ':</b></font>';
var cell2 = row.insertCell(1);
var element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer"+a;
cell2.appendChild(element1);
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = String.fromCharCode(67+i);
cell3.appendChild(element2);
i++;
a++;
}
}
My HTML Form:
<table>
<tr>
<form method=post name="submitform" action="verify-qedit.jsp">
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</form>
</tr>
</table>
When I submit the form, I only can retrieve the parameters not created by the above javascript. It only works in compatibility mode - IE 8 standards and below. Please help because I have spent days trying to find out before posting this question.
Does this work on all the browsers you are targetting?
http://jsfiddle.net/4nbB5/1
function addNewAnswer(tableID) {
var rowCount, row, cell1, cell2, cell3, element1, element2, char;
var i = 0;
var table = document.getElementById(tableID);
while (i < 10) {
rowCount = table.rows.length;
row = table.insertRow(rowCount);
cell1 = row.insertCell(0);
char = String.fromCharCode(65 + i);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + char + ':</b></font>';
cell2 = row.insertCell(1);
element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer" + i;
cell2.appendChild(element1);
cell3 = row.insertCell(2);
element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = char;
cell3.appendChild(element2);
i++;
}
}
addNewAnswer('foo');
All I did was remove 'a', and declare 'i', change 'if' to while, changed 67 in fromCharCode to 65.. Looked to be what you may have wanted at some point so I stopped.
The problem had nothing to do with the javascript. It was because I was putting the form tag in the wrong place within the table after the tr tag instead of after the td tag.
<table>
<tr>
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</tr>
</table>
I am making an invoice system, I want to get the price textbox to be automatically calculated. I am having a table of random rows, in the invoice. How do I do it via a JS function on price text box.
var rowCount = 0;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
cell5.appendChild(element4);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "price[]";
cell5.appendChild(element4);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<form action="" method="post" enctype="multipart/form-data">
invoice:
<INPUT type="text" name="invoice id" />
<TABLE id="dataTable" width="350px" border="1" style="border-collapse:collapse;">
<TR>
<TH>Select</TH>
<TH>Sr. No.</TH>
<TH>Item</TH>
<TH>Cost</TH>
<TH>Qty</TH>
<TH formula="cost*qty" summary="sum">Price</TH>
</TR>
<TR>
<TD>
<INPUT type="checkbox" name="chk[]" />
</TD>
<TD> 1 </TD>
<TD>
<INPUT type="text" name="item[] " /> </TD>
<TD>
<INPUT type="text" name="qty[]" /> </TD>
<TD>
<INPUT type="text" name="cost[]" /> </TD>
<TD>
<INPUT type="text" name="price[]" /> </TD>
</TR>
</TABLE>
<input type="submit" />
</form>
Update anno 2022
const container = document.getElementById("container")
const table = document.querySelector("#dataTable tbody");
const totalField = document.getElementById("total");
const addRow = () => {
const newRow = table.firstElementChild.cloneNode(true);
newRow.querySelectorAll("input").forEach(inp => inp.type === "checkbox" ? inp.checked = false : inp.value = "")
table.appendChild(newRow)
newRow.querySelectorAll("td")[1].textContent = table.querySelectorAll("tr").length;
};
const removeRow = () => {
table.querySelectorAll("[type=checkbox]:checked").forEach(chk => chk.closest("tr").remove())
table.querySelectorAll("tr td:nth-child(2)").forEach((cell, i) => cell.textContent = i + 1);
totalIt();
};
const totalIt = (e) => {
if (e && e.target.matches("[type=checkbox]")) return;
const qtyFields = [...document.getElementsByName("qty[]")];
let total = qtyFields.map(qtyField => {
const parent = qtyField.closest("tr");
const qty = +qtyField.value;
const cost = +parent.querySelector(".cost").value;
const priceField = parent.querySelector(".price");
let price = cost * qty;
if (isNaN(price)) price = 0;
priceField.value = price.toFixed(2);
return price;
}).reduce((a, b) => a + b)
totalField.value = total ? total.toFixed(2) : "0.00";
};
container.addEventListener("click", function(e) {
const tgt = e.target;
if (!tgt.id) return;
if (tgt.id === "add") addRow();
else if (tgt.id === "remove") removeRow();
})
container.addEventListener("input", totalIt);
#dataTable {
width: 350px;
margin: 5px;
}
#dataTable tr,
td,
th {
border: 1px solid black;
border-collapse: collapse;
}
<div id="container">
<input type="button" value="Add Row" id="add" />
<input type="button" value="Delete checked Rows" id="remove" />
<form action="" method="post" enctype="multipart/form-data">
invoice:<input type="text" name="invoice id" />
<table id="dataTable">
<thead>
<tr>
<th>Select</th>
<th>Sr. No.</th>
<th>Item</th>
<th>Qty</th>
<th>Cost</th>
<th formula="cost*qty" summary="sum">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="chk[]" /></td>
<td>1</td>
<td><input type="text" name="item[] " /></td>
<td><input type="text" class="qty" name="qty[]" /></td>
<td><input type="text" class="cost" name="cost[]" /></td>
<td><input type="text" class="price" name="price[]" /></td>
</tr>
</tbody>
</table>
total: <input type="text" readonly="readonly" id="total" /><br />
<input type="submit" />
</form>
Old answer
DEMO
You had cost and QTY in the wrong cells according to the header cell!!!
<TD> <INPUT type="text" id="qty1" name="qty[]"/> </TD>
<TD> <INPUT type="text" id="cost1" name="cost[]" /> </TD>
<TD> <INPUT type="text" id="price1" name="price[]" /> </TD>
New code:
function calc(idx) {
var price = parseFloat(document.getElementById("cost"+idx).value)*
parseFloat(document.getElementById("qty"+idx).value);
// alert(idx+":"+price);
document.getElementById("price"+idx).value= isNaN(price)?"0.00":price.toFixed(2)
}
window.onload=function() {
document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
}
var rowCount =0;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "item[]";
element3.required = "required";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "qty[]";
element4.id = "qty"+rowCount;
element4.onkeyup=function() {calc(rowCount);}
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "cost[]";
element5.id = "cost"+rowCount;
element5.onkeyup=function() {calc(rowCount);}
cell5.appendChild(element5);
var cell6 = row.insertCell(5);
var element6 = document.createElement("input");
element6.type = "text";
element6.name = "price[]";
element6.id = "price"+rowCount
cell6.appendChild(element6);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
Here is a total - you can actually replace calc with this if you cut and paste calc into where I do calc(i)
function totalIt() {
var qtys = document.getElementsByName("qty[]");
var total=0;
for (var i=1;i<=qtys.length;i++) {
calc(i);
var price = parseFloat(document.getElementById("price"+i).value);
total += isNaN(price)?0:price;
}
document.getElementById("total").value=isNaN(total)?"0.00":total.toFixed(2);
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<form action="" method="post" enctype="multipart/form-data">
invoice:<INPUT type="text" name="invoice id"/>
<TABLE id="dataTable" width="350px" border="1" style="border-collapse:collapse;">
<TR>
<TH>Select</TH>
<TH>Sr. No.</TH>
<TH>Item</TH>
<TH>Cost</TH>
<TH>Qty</TH>
<TH formula="cost*qty"summary="sum">Price</TH>
</TR>
</TABLE>
<input type="submit" />
And script:
<SCRIPT language="javascript">
var rowCount =0;
function calculatePrice(qtyElement, costElement, priceElement) {
priceElement.value = qtyElement.value * costElement.value;
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
element3.onchange = function(){
calculatePrice(this, this.parentElement.parentElement.childNodes[4].childNodes[0], this.parentElement.parentElement.childNodes[5].childNodes[0]);
};
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
element4.onchange = function(){
calculatePrice(this.parentElement.parentElement.childNodes[3].childNodes[0], this, this.parentElement.parentElement.childNodes[5].childNodes[0]);
};
cell5.appendChild(element4);
var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "price[]";
cell6.appendChild(element5);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
addRow('dataTable');
</SCRIPT>
Just bind the calculation to, for example, a key event. You should create the first invoice row also via JS.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
cell5.appendChild(element4);
var cell5 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "price[]";
cell5.appendChild(element5);
var calcPrice = function() {
try {
element5.value = element3.value * element4.value;
} catch(e) {
}
}
element3.onkeyup = calcPrice;
element4.onkeyup = calcPrice;
}
You may implement the calculations inside a function that is called when the onchange event is fired in some of the input fields (the last of a row or the first of the next row calculates the previuos row price).
<script type="text/javascript">
$(function(){
//add new row
$('.add').click(function(){
var tr = '<tr>'+
'<td><input type="text" name="product_name[]" class="form-control product_name"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="price[]" class="form-control price"></td>'+
'<td><input type="text" name="amount[]" class="form-control amount"></td>'+
'<td><input type="button" class="btn btn-danger remove" value="Remove"></td>'+
'</tr>';
$('.details').append(tr);
});
// end
// total amount
$('.details').delegate('.quantity,.price','keyup',function(){
var tr = $(this).parent().parent();
var price = tr.find('.price').val();
var qty = tr.find('.quantity').val();
var amount = price * qty;
tr.find('.amount').val(amount);
total();
});
// end
// delete row
$('.details').delegate('.remove','click',function(){
var con = confirm("Do you want to remove it ?");
if(con)
{
$(this).parent().parent().remove();
total();
}
});
// end
//get pay
$('.pay').change(function(){
var subtotal = $('.subtotal').val()-0;
var get = $(this).val()-0;
$('.return').val(get - subtotal);
});
// end
});
</script>
<script type="text/javascript">
// for updating the tax while writing the price .
function changeTax(){
var price = document.getElementById("price").value;
var q = document.getElementById("quantity").value;
var np = Number(price);
var tax = (0.15 * np)*q;
<!-- how to diferenciate concatinate anad plus sign-->
document.getElementById("amount").value = q * np;
var amount = document.getElementById("amount").value;
document.getElementById("tax").value = tax;
document.getElementById("subtotal").value = Number(tax) + Number(amount);
}
</script>
<script>
$(function() {
});
</script>