Get total value of a particular column in multiple row table - javascript

I created a table where I can dynamically add multiple rows to it. There's a column to add cost. Now I want to
get total cost value of each row at the bottom of the table. How can I get this using JavaScript?
Here is my html code for dynamic table.
<table>
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th cost</th>
</tr>
</thead>
<tbody id="body">
<tr>
<th>1</th>
<td>
<input type="text" id="title" name="title[]" />
</td>
<td>
<input type="text" id="cost" name="cost[]" />
</td>
</tr>
</tbody>
</table>
Javascript function:
$(function(){
$('.addrow').click(function(){
addrow();
});
function addrow()
{
var row =($('#body tr').length-0)+1;
var tr ='<tr>'+
'<th>'+row+'</th>'+
'<td><input type="text" id="title" name="title[]" ></td>'+
'<td><input type="text" id="cost" name="cost[]" /></td>'+
'</tr>';
$('#body').append(tr);
}
});

You should iterate the input tags that belong to the table and have an id starting with "cost".
Also, you can not add the row directly to the body, you want to add it after the last row already created.
Try out this (edit:) fiddle (old habits die hard) snippet .
$(document).ready(function(){
$('#addRow').click(function(){
addRow();
});
$('#totalRow').click(function(){
totalRow();
});
function addRow()
{
var rowId = $('#myTable tr').length;
$('#myTable > tbody:last-child').append(
'<tr><th>' + rowId + ' </th>' +
'<td><input type="text" id="title' + rowId + '" /></td>' +
'<td><input type="text" id="cost' + rowId + '"</td></tr>'
);
}
function totalRow()
{
var rowId = $('#myTable tr').length;
var val = 0;
$("#myTable [id^=cost]").each(function() {
val += parseFloat($(this).val());
});
$('#myTable > tbody:last-child').append(
'<tr><th>T</th>' +
'<td><input type="text" id="totalRow" value="TOTAL" /></td>' +
'<td><input type="text" id="totalCost" value="' + val +'" /></td></tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addRow">Add row</div>
<div id="totalRow">Calculate total row</div>
<br>
<table id="myTable">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>
<input type="text" id="title1" value="Example" />
</td>
<td>
<input type="text" id="cost1" value="25" />
</td>
</tr>
</tbody>
</table>
Hope it helps!

If text inputs are the only inputs used, try using https://api.jquery.com/input-selector/ to get all the input selectors.
You can iterate through the input selectors, aggregate the values to give you the total.
NOTE: As mentioned in the comments, do not use same id for all the input tags. It is not a best practice

Related

Add row and td element and a checkbox in the table

I have the following table structure
<form method=POST class='form leftLabels'>
<table >
<tr >
<th >Code:</th>
<td ><input type='text' name='f[id]' size='60' value='10' /></td>
</tr>
<tr ><th >Name:</th>
<td ><input type='text' name='f[name]' size='60' value='Aa' /></td>
</tr>
// <<<< Here I would like to add a row
<tr >
<td class=' nogrid buttonsClass'><button type=submit>Save</button>
</td>
</tr>
</table>
</form>
The row that I am trying to add should have the following html:
<tr>
<th> Delete the record?</th>
<td><input type='checbox' name='delete' value=1></td>
</tr>
I have the following Javascript / jQuery code:
var trCnt=0;
$('table tr').each(function(){
trCnt++;
});
rowToInsertCheckbox = trCnt - 1;
$('table').after(rowToInsertCheckbox).append(
$(document.createElement('tr')),
$(document.createElement('td').html('Delete the record'),
$(document.createElement('td').html('Checkbox here?')),
);
which does find the right row after which the insert should be done, but the code does not work.
after() adds the new content after the target element, but outside it. tr need to be inside the table. In addition you need to append the td to the tr, not the table.
To place the new tr in your target position you can select the last tr in the table and use insertBefore(), like this:
let $newRow = $('<tr />').insertBefore('table tr:last');
$('<td>Delete the record?</td>').appendTo($newRow);
$('<td><input type="checkbox" name="delete" value="1"></td>').appendTo($newRow);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" class="form leftLabels">
<table>
<tr>
<th>Code:</th>
<td><input type="text" name="f[id]" size="60" value="10" /></td>
</tr>
<tr>
<th>Name:</th>
<td><input type="text" name="f[name]" size="60" value="Aa" /></td>
</tr>
<tr>
<td class="nogrid buttonsClass"><button type="submit">Save</button></td>
</tr>
</table>
</form>
One way to locate the row after which the content should be added is:
var tr = $("th").filter(function () {
return $(this).text() == "Name:";
}).closest("tr");
Then add the row:
$(tr).after("<tr><th> Delete the record?</th><td><input type='checkbox' name='delete' value=1></td></tr>");
$(document).ready(function() {
var tr = $("th").filter(function() {
return $(this).text() == "Name:";
}).closest("tr");
$(tr).after("<tr><th>Delete the record?</th>" +
"<td><input type='checkbox' name='delete' value=1></td>" +
"</tr>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method=POST class='form leftLabels'>
<table>
<tr>
<th>Code:</th>
<td><input type='text' name='f[id]' size='60' value='10' /></td>
</tr>
<tr>
<th>Name:</th>
<td><input type='text' name='f[name]' size='60' value='Aa' /></td>
</tr>
<tr>
<td class=' nogrid buttonsClass'><button type=submit>Save</button>
</td>
</tr>
</table>
</form>

A function not working when creating new row on table

I have a html table where I add rows dynamically when user clicks on a button. Two cell's number of each row of my table, should be multiplied. I made a function that can multiply 2 cell's number but when I create a new row by pressing add button the function does not work on the new row, it always works on first row on the table.
Here is HTML code:
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price" oninput="calculate()">
</td>
<td>
<input type="text" id="qt" oninput="calculate()">
</td>
<td>
<input type="text" id="ttl" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
</div>
And here is the JavaScript code:
let temp_td = '<tr>' +
'<th scope="row">1</th>' +
'<td><label><input type="text" name="name"></label></td>' +
'<td><label><input type="text" id="price" oninput="calculate()"></td>' +
'<td><input type="text" id="qt" oninput="calculate()"></td>' +
'<td><input type="text" id="ttl" name="total"></td>' +
'<td><button class="remove">-</button></td>' +
'</tr>';
$(function () {
$('tbody').sortable();
$('#addRow').click(function () {
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function () {
$(this).parents('tr').remove();
});
$('#getValues').click(function () {
const total = [];
let sum = 0;
$('input[name="total"]').each(function (i, elem) {
total.push($(elem).val())
});
for (let i = 0; i < total.length; i++) {
sum += Number(total[i])
}
console.log(total.join(','));
console.log(total);
console.log(sum);
document.getElementById('subtotal').innerHTML = sum;
document.getElementById('total').innerHTML = sum + (sum * 5 / 100);
// document.getElementById('total22').innerHTML = sum;
})
});
function calculate() {
var price = document.getElementById('price').value;
var qt = document.getElementById('qt').value;
var ttl = document.getElementById('ttl');
var multiply = price * qt;
ttl.value = multiply;
}
I tried to change so many things, but it's not working.
You cannot duplicate the IDs in HTML. You can save the row number in a variable which you increment every time you add a new row, and use that variable to generate the IDs:
$(function() {
let row = 1;
$('#addRow').click(function() {
row++;
let temp_td = '<tr><th scope="row">' + row + '</th><td><label><input type="text" name="name"></label></td><td><label><input type="text" id="price' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="qt' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="ttl' + row + '" name="total"></td><td><button class="remove">-</button></td></tr>';
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
function calculate(r) {
var price = document.getElementById('price' + r).value;
var qt = document.getElementById('qt' + r).value;
var ttl = document.getElementById('ttl' + r);
var multiply = price * qt;
ttl.value = multiply;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="qt1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="ttl1" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
You can also do that to the names if you like. I didn't do that in the code above because it is not essential for this answer.
Alternatively, you can pass the element itself to the calculate() function and then find the other "sibling" elements using jQuery. So you don't need IDs at all.

Get data from table row to Javascript

I have table . There are three columns : Name , Price and button "Make Order". I must get data from each row to my Javascript. Each input have id such as productName and productPrice .
Table code:
<table border="2px">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<c:forEach items="${productList}" var="product" varStatus="status">
<tr>
<form>
<td> ${product.getProductName()}</td>
<input type="hidden" id="productName" name="productName" value=${product.getProductName()}>
<td>${product.getPrice()}</td>
<input type="hidden" id="productPrice" name="productPrice" value=${product.getPrice()}>
<td><input type="submit" onclick="makeOrder()" value="Make Order"></td>
</form>
</tr>
</c:forEach>
</table>
And my js:
<script type="text/javascript">
function makeOrder() {
var n=document.getElementById("productName").value;
var p=document.getElementById("productPrice").value;
alert("n="+n);
alert("p="+p);
//var win=window.open("/user/makeOrder?productName=" + n + "&productPrice=" + p);
}
But when I click on my button I always alert first row of my table .
How can I alert other row ?
Use a unique row id for each row and pass that id with makeOrder() function and then find child elements inside that row whose id is passed in function...
Here is working example....
function makeOrder(rowId)
{
var n=document.getElementById(rowId).childNodes[5].value;
var p=document.getElementById(rowId).childNodes[9].value;
alert("n="+n);
alert("p="+p);
//var win=window.open("/user/makeOrder?productName=" + n + "&productPrice=" + p);
}
<table border="2px">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr id="row1">
<form>
<td>P1</td>
<input type="hidden" id="productName" name="productName" value="P1">
<td>$5</td>
<input type="hidden" id="productPrice" name="productPrice" value="5">
<td><input type="button" onclick="makeOrder('row1')" value="Make Order"></td>
</form>
</tr>
<tr id="row2">
<form>
<td>P2</td>
<input type="hidden" id="productName" name="productName" value="P2">
<td>$6</td>
<input type="hidden" id="productPrice" name="productPrice" value="6">
<td><input type="button" onclick="makeOrder('row2')" value="Make Order"></td>
</form>
</tr>
</table>
You could call a function that gives all inputs with name productName, see below.
var n=document.getElementsByName("productName").value;
var p=document.getElementsByName("productPrice").value;
for(var i = 0; i < n.length; i++) {
alert("row 1: " + n[i].value + p[i].value);
}
This should return all your rows. Each alert will show the data of 1 row.

Appending data to <tfoot> section

I have a table that populates with contents from a database. A user should be able to add as many new entries as they want to the table (let's ignore the 'save' button for now).
I attempt to add new rows to the table with
$("#businesscategorytable tfoot").append(addNewRow);
where addNewRow is formatted like the other rows in the table. However, this procedure does not work. What is even more confusing is that a similar module was used in a separate page of the project I'm working on and everything functions properly.
Here's a Stack Snippet that provides a bare-bones mock-up of what I'm working with:
$(function() {
//Remove Row Function for Business Category Tables
$("table[id='businesscategorytable']").on("click", "input[id='btnDeleteRow']", function() {
$(this).closest('tr').hide(); //hiding rows instead of removing so we only commit on 'Save'
});
//End Remove Row Function for Tables
//Add Row Function for Business Category Tables
$("input[id='btnAddBusinessRow']").click(function() {
var addNewRow = "<tr><td style=\"display: none\"><input type=\"hidden\" class=\"hdnBusinessCatId\" id=\"hdnBusinessCatId" + idCount + "\" />" +
"<td><input type=\"text\" id=\"businessCat" + idCount + "\" size=\"12\"></td>" +
"<td><input type=\"text\" id=\"businessColor" + idCount + "\" size=\"8\" value=\"$\"></td>" +
"<td><input type=\"button\" id=\"btnDeleteRow\" value=\"Delete\"\"></td>" +
"</tr>";
$("#businesscategorytable tfoot").append(addNewRow);
idCount++;
});
//End Add Row Function
});
<table border="1" id="businesscategorytable">
<thead>
<tr style="color:white;background-color:darkgray">
<th>Category Name</th>
<th>Color on Map</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display: none">
<input type="hidden" class="hdnBusinessCatId" id="0" />
</td>
<td>
<input type="text" id="txtCategoryName0" size="12" value="0">
</td>
<td>
<input type="text" id="txtCategoryId0" size="8" value="Red">
</td>
<td>
<input type="button" id="btnDeleteRow" value="Delete">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td style="display: none">
<input type="hidden" class="hdnBusinessCatId" id="hdnBusinessCatId0" />
</td>
<td>
<input type="text" id="businessCat0" size="12" />
</td>
<td>
<input type="text" id="businessColor0" value="$" size="8" />
</td>
<td>
<input type="button" id="btnDeleteRow" value="Delete" />
</td>
</tr>
</tfoot>
</table>
<input type="button" id="btnAddBusinessRow" value="Add" />
Any ideas as to why this may not be working?
If you check your console you can see that idCount is undefined you need to declare idCount as a variable somewhere. I did that and it seemed to work how you declare idCount is up to you but it should definitley not conflict with the current id's you set it up with. Here's a JS Bin of that. I just added var idCount=1 before the click handler. It probably worked on the other page because idCount was declared there.

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

Categories

Resources