Sum values in column - javascript

I can't sum the subtotals of an HTML column table using javascript. I need to sum the 5th column and put the result in a textbox so the costumer can see the totals of his bill. The thing is, I can't use database because it is a table that doesn't INSERT the value in the database until I hit the final button. Any help would be appreciated. Thanks a lot
var arr2 = "";
$('#añadir').click(function() {
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
var subtotal = (cantidad * punitario)
if (id_pla != "" && cantidad != "") {
var row = table.insertRow(cant);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = cant;
cell1.innerHTML = id_pla;
cell2.innerHTML = pla;
cell3.innerHTML = cantidad;
cell4.innerHTML = punitario;
cell5.innerHTML = subtotal;
cant++;
arr2 += id_pla + "," + cantidad + ","
$('#arr').val(arr2);
}
validar();
});
This is the HTML code
<table id="tablaC" class="table table-hover">
<thead>
<tr>
<th>ID Pedido</th>
<th>ID Plato</th>
<th>Plato</th>
<th>Cantidad</th>
<th>Precio Unitario</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<input id="arr" name="arr" value="" />
<br>
<br/>
<input class="btn btn-info" type="submit" value="Crear Registro" id="registro">
</form>
<p></p>

I notice several issues in your files codes, you should fix them in order to make this work:
1)
To compare with "" You should use strict equality "!==" instead of "!="
if (id_pla !== "" && cantidad !== "") {
instead of:
if (id_pla != "" && cantidad != "") {
2) "$" is not defined as a variable, unless you refer to jQuery.
/*here*/ $('#añadir').click(function() {
3) Ids missing in your HTML code:
Here you are saying:
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
But you are not giving any id to this elements on your html. It should be like this:
<th>ID Pedido</th>
<th id="plato_id">ID Plato</th>
<th id="plato_nombre">Plato</th>
<th id="cantidad">Cantidad</th>
<th id="plato_precio">Precio Unitario</th>
<th>Subtotal</th>

Related

"Undefined is not an object" When trying to reference a cell in HTML

I'm trying to make a table with data from the user on a website. I added the option to erase the row but I get an error
"undefined is not an object (evaluating 'table.rows[i].cells[3]')"
My code works if I use a fixed table, but with the script to make the table editable it doesn't work, here is my code:
<html>
<head>
<title>Remove HTML Table Selected Row</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
td:last-child{background-color: #F00;color:#FFF;cursor: pointer;
font-weight: bold;text-decoration: underline}
</style>
</head>
<body>
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
</tr>
</table>
</div>
<div class="tab tab-2">
First Name :<input type="text" name="fname" id="fname">
Last Name :<input type="text" name="lname" id="lname">
Age :<input type="number" name="age" id="age">
<button onclick="addHtmlTableRow();">Add</button>
</div>
</div>
<script>
var rIndex,
table = document.getElementById("table");
// check the empty input
function checkEmptyInput()
{
var isEmpty = false,
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value;
if(fname === ""){
alert("First Name Connot Be Empty");
isEmpty = true;
}
else if(lname === ""){
alert("Last Name Connot Be Empty");
isEmpty = true;
}
else if(age === ""){
alert("Age Connot Be Empty");
isEmpty = true;
}
return isEmpty;
}
// add Row
function addHtmlTableRow()
{
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if(!checkEmptyInput()){
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value,
edit = "Edit"
cell1.innerHTML = fname;
cell2.innerHTML = lname;
cell3.innerHTML = age;
cell4.innerHTML = edit;
// call the function to set the event to the new row
selectedRowToInput();
}
}
// display selected row data into input text
function selectedRowToInput()
{
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("fname").value = this.cells[0].innerHTML;
document.getElementById("lname").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
var index, table = document.getElementById('table');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[3].onclick = function() //Line with the error
{
var c = confirm("do you want to delete this row");
if(c === true)
{
index = this.parentElement.rowIndex;
table.deleteRow(index);
}
//console.log(index);
};
}
</script>
</body>
</html>
Any ideas what might the problem be?, Thanks a lot
you don't need to loop inside function addHtmlTableRow() just add class to the Edit then setup event handler for dynamically added element using
document.addEventListener('click',function(e){
if(e.target){
//do something
}
});
var rIndex,
table = document.getElementById("table");
// check the empty input
function checkEmptyInput() {
var isEmpty = false,
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value;
if (fname === "") {
alert("First Name Connot Be Empty");
isEmpty = true;
} else if (lname === "") {
alert("Last Name Connot Be Empty");
isEmpty = true;
} else if (age === "") {
alert("Age Connot Be Empty");
isEmpty = true;
}
return isEmpty;
}
// add Row
function addHtmlTableRow() {
// get the table by id
// create a new row and cells
// get value from input text
// set the values into row cell's
if (!checkEmptyInput()) {
var newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
cell4 = newRow.insertCell(3),
fname = document.getElementById("fname").value,
lname = document.getElementById("lname").value,
age = document.getElementById("age").value,
edit = 'Edit';
cell1.innerHTML = fname;
cell2.innerHTML = lname;
cell3.innerHTML = age;
cell4.innerHTML = edit;
cell4.className = "delete"; // <== add this class
// call the function to set the event to the new row
selectedRowToInput();
}
}
// display selected row data into input text
function selectedRowToInput() {
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
// get the seected row index
rIndex = this.rowIndex;
document.getElementById("fname").value = this.cells[0].innerHTML;
document.getElementById("lname").value = this.cells[1].innerHTML;
document.getElementById("age").value = this.cells[2].innerHTML;
};
}
}
selectedRowToInput();
// for deleting row
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('delete')) {
if (confirm("do you want to delete this row")) {
e.target.parentElement.remove();
}
}
});
td:last-child {
background-color: #F00;
color: #FFF;
cursor: pointer;
font-weight: bold;
text-decoration: underline;
}
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
</tr>
</table>
</div>
<div class="tab tab-2">
First Name :<input type="text" name="fname" id="fname">
Last Name :<input type="text" name="lname" id="lname">
Age :<input type="number" name="age" id="age">
<button onclick="addHtmlTableRow();">Add</button>
</div>
</div>
Basically At the first iteration of the loop try to access third <td> (cell) which doesn't exist.
<table id="table" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
<tr>
<!-- there is no cell -->
</tr>
</table>
Therefore undefined error shows up.
you can remove it as it has no use.
And
You should execute the loop after inserted some data into the table.
Just wrap the loop in a condition. (if you remove the <tr> then our condition should be table.rows.length > 1)
if(table.rows.length > 2){
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[3].onclick = function()
{
var c = confirm("do you want to delete this row");
if(c === true)
{
index = this.parentElement.rowIndex;
table.deleteRow(index);
}
//console.log(index);
};
}
}
Arrays in Javascript starts at 0. In your example, this means that:
- rows[0] = Header row
- rows[1] = First data row
- rows[2] = Second data row
And so forth. Your for loop starts counting a 1.
Therefore, your for loop tries to access the second row in the table, but when the page first loads, this row doesn't contain any cells.
This is why the script says that undefined is not an object. The for loop will try to access row[1].cells[3] but row[1] doesn't have any cells. So, you're trying to access a cell that doesn't exist.

How to delete a row from HTML table using the button which is in the next cell of the data entered?

This is my code which I was working on. Basically it is the Library Management Project for the final semester in my college.
Now my question is how to delete a row when we click that row's delete button.
<table border="1" id="student_tb1" class="table table-bordered" style="display: none;" contenteditable="true">
<tr>
<td>Sr. No.</td>
<td>Class</td>
<td>Roll no</td>
<td>Name</td>
</tr>
</table>
<script type="text/javascript">
function addStudent(){
var maxRows = 10;
var table = document.getElementById("student_tb1");
var text1 = document.getElementById("student_textbox1").value;
var text2 = document.getElementById("student_textbox2").value;
var text3 = document.getElementById("student_textbox3").value;
var x = document.getElementById("book_tb1").rows.length;
var message;
message = document.getElementById("message");
message.innerHTML = "";
if(x <= maxRows) {
if(text1 == "select" ){
message.innerHTML = "select the class !! "
}
else if(text2 == "" || isNaN(text2) || text2 < 0 || text2 > 100 || text2 == 0){
message.innerHTML = "your roll no may be between 0 and 101 "
}
else if (text3 == "") {
message.innerHTML = "enter the name"
}
else{
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell2.innerHTML = text1;
cell3.innerHTML = text2;
cell4.innerHTML = text3;
for (var i = 0; i < x; i++) {
cell1.innerHTML = i+1;
}
}
alert("Data has been inserted successfully!");
}|
}
</script>
Result:
Sr. No. |Class |Roll no |Name |Action
1 |BSCIT-3 |010 |vishesh |Delete button
You can call this function:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
and make your delete button html:
<input type="button" value="Delete" onclick="deleteRow(this)"/>

If statement to change new row added to quantity added

Hello I'm fairly new here so please correct me if I make any formatting or question errors!
I am attempting to create a simple shopping basket file and need some help getting the quantity of items within the basket to change. At the moment I can create a button that adds a new row to a table and fills it, I am just having a shortfall at getting the function to check if the item is already in the table and only update the quantity cell if it is. I am useless with IF statements, so any help would be more than appreciated!
<!DOCTYPE html>
<html>
<head>
<script>
function additem1() {
var table = document.getElementById("basket");
var row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = "Shorts (f)";
cell2.innerHTML = "Stone Wash";
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";
;
}
</script>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2> List of Items </h2>
<table border="1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<tr>
<td> Shorts (F) </td>
<td> Stone wash Denim shorts </td>
<td> 20 </td>
<td> 25.90 </td>
<td> <button onclick= "additem1()"> Add Item To Basket </button> </td>
</table>
<table id="basket" border = "1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<th colspan="2"> Add / Remove items </th>
</tr>
</table>
as you can see the first table holds the item information, and the second table holds the basket information.
Please consider to go deep on js coding; you can consider to check if the element already exist, then if so increment the quantity.
I made your code a little more generic, but for a working basket there is more to do, that's your job.
Code:
function additem1(e) {
var oRow = e.parentNode.parentNode
var prod = oRow.cells[0].innerHTML;
var des = oRow.cells[1].innerHTML;
var table = document.getElementById("basket");
var row1 = GetCellValues(prod);
if (typeof row1 === 'undefined') {
row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = prod;
cell2.innerHTML = des;
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";;
} else {
row1.cells[2].innerHTML = parseInt(row1.cells[2].innerHTML) + 1
}
}
function GetCellValues(prod) {
var table = document.getElementById('basket');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
if (table.rows[r].cells[c].innerHTML == prod) return table.rows[r];
}
}
return
}
Demo: http://jsfiddle.net/85o9yz02/

How to access the dynamically assigned value for a cell in the dynamic html table in java script within another java script function

I have a problem with accessing the cell value that I have assigned to a cell in the dynamic table using a addRow js function.Now I want to access that value from another js function function re(cal) on button click but when I try to access that value it says that value/innerHtml is undefined.
Here is my html file
<table id="calorie">
<tr><hr></tr>
<tr>
<td><label class="z"><b>Food Item</b></label></td>
<td> <?php
include("connection.php");
$query = "SELECT * FROM foodcataloge";
$result = mysql_query($query) or die("Unable to query Food");
$option = '';
while($row=mysql_fetch_array($result)) {
$option .= '<option value='.$row['FoodCataloge_CalorieAmount'].'>'. $row['FoodCataloge_FoodName'].'</option>';
}
?>
<select name="FoodCataloge_FoodName" id="food" onchange="updateText();"><?php echo $option; ?></select></td>
</tr>
<tr>
<td><label class="z"><b>Portion </b></label></td>
<td> <input type="text"class="span3" name="foodpor" id="foodpor" onchange="pupdate();"></td>
</tr>
<tr>
<td><label class="z"><b>Calorie amount per portion </b></label></td>
<td> <input type="text"class="span3" name="calamount" id="calamount" ></td>
</tr>
<tr><td><label class="z"><b>Number of Calories</b></label></td>
<td> <input type="text" class="span3"name="calo" id="calo"></td>
</tr>
<tr>
<tr><td><label class="z"><b>Total</b></label></td>
<td> <input type="text" class="span3"name="res" id="res"></td>
</tr>
<tr>
<td></td><td></td>
<td><input type = "button" value = "Add" onclick = "showDiv(),addRow('cal')"></td>
<td><input type = "button" value = "Remove" onclick = "deleteRow('cal')"></td>
<td><input type = "button" value = "Calculate" onclick = "re('cal')"></td></tr>
</table>
<br><br><br><br>
<table id="cal" class="table span2" >
<thead>
<th width="30px" id="l1" hidden="true"><label class="z"><b>Remove</b></label></th>
<th width="30px" id="l2"hidden="true"><label class="z"><b>Food</b></label></th>
<th width="30px" id="l3" hidden="true"><label class="z"><b>Portion</b></label></th>
<th width="30px" id="l4" hidden="true"><label class="z"><b>Calories</b></label></th>
<th width="30px" id="l5" hidden="true"><label class="z"><b> Total</b></label></th>
</thead>
</table>
my dynamic table is cal
Here is my js file
function re(cal){
var table = document.getElementById(cal);
var rowCount = table.rows.length;
alert(rowCount);
//or (var i=1;i<rowCount;i++){
var sum =document.getElementById(cal).rows[1].cells[3].value;
alert(sum);
//}
}
function addRow(cal) {
document.getElementById('cal').style.border = "8px solid #718294";
var table = document.getElementById(cal);
var rowCount = table.rows.length;
var cellCount= document.getElementById(cal).rows[0].cells.length;
var row = table.insertRow(rowCount);
row.id="row"
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[]";
element2.value=document.getElementById('food').options[document.getElementById('food').selectedIndex].text;
element2.setAttribute('id', 'cell2' + rowCount);
cell2.appendChild(element2);
var cell3= row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
element3.value=document.getElementById('foodpor').value;
element3.setAttribute('id', 'cell3' + rowCount);
cell3.appendChild(element3);
var cell4= row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.value=document.getElementById('calo').value;
element4.setAttribute('class', 'clu');
element4.setAttribute('id', 'cell4' + rowCount);
cell4.appendChild(element4);
var cell5= row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtbox[]";
element5.setAttribute('id', 'cell5' + rowCount);
cell5.appendChild(element5);
//cell2.innerHTML=document.getElementById('food').options[document.getElementById('food').selectedIndex].text;
//cell3.innerHTML=document.getElementById('foodpor').value;
//cell4.innerHTML=document.getElementById('calo').value;
document.getElementById('food').value = '';
document.getElementById('foodpor').value='';
document.getElementById('calo').value='';
document.getElementById('calamount').value='';
}
function deleteRow(cal) {
try {
var table = document.getElementById(cal);
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);
}
}
All the other things working fine but from the function function re(cal) alert the sum as undefined but I expect it to be the value of that selected cell..
Please tell me what I am doing wrong!
From where are you calling re(cal)? the alert? before or after the table creation. If before, that's why it's undefined.

HTML Table cell - Recovering Values

I have a html table with a dynamic rows list, When I delete one of these rows I want to recover the value of the column 3 on the selected row to change an output text with the total value...
How do I do it with jquery or javascript ?
<div id="ven_mid">
<table id="tbprodutos" style="width:80%;margin:0 auto;float:left;text-align:center;">
<tr class="titulo">
<th>Referência</th>
<th>Numeração</th>
<th>Qtd</th>
<th>Valor - R$</th>
<th>Código</th>
<th>-</th>
</tr>
</table>
</div>
<script>
function deleteRow(i){
// here i need to remove the value "valor"
// of the selected row of the total.
document.getElementById('tbprodutos').deleteRow(i);
}
</script>
--- Add Row Script ---
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
var ref = "";
var valor = "";
var id = "";
var cor = "";
var mat = "";
var tot = document.getElementById('valortotal').value;
$.ajax({
type: "POST",
url: "System/ProcessaProdutos.jsp",
data: "pro_barras="+barra,
success: function(data){
var retorno = data.split(" ");
ref = (retorno[0]);
valor = (retorno[1]);
id = (retorno[2]);
mat = (retorno[3]);
cor = (retorno[4]);
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>Ref: '+ref+' - '+mat+' '+cor+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td class="tbvalor">'+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
var newCell5 = newRow.insertCell(5);
newCell5.innerHTML = '<td><input type="button" value="Remover" onclick="deleteRow(this.parentNode.parentNode.rowIndex)"/></td>';
document.getElementById('ref').value = 'Referência: '+ref+' - '+mat+' '+cor;
document.getElementById('imgsrc').src = './?acao=Img&pro_id='+id;
updateTotal();
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
}
});
return false;
}
});
</script>
--- New "update total" function that solved the problem --
function updateTotal(){
var total = 0;
var rows = $("#tbprodutos tr:gt(0)");
rows.children("td:nth-child(4)").each(function() {
total += parseInt($(this).text());
});
document.getElementById('valortotal').value = total;
}
To expand on what Bartdude said, here is a more usable example. Lets say you have a table with the structure
<table id = 'tableData'>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
<tr>
<td class = 'col1'>1.1</td>
<td class = 'col2'>1.2</td>
<td class = 'col3'>1.3</td>
<td class = 'col4'>1.4</td>
<td class = 'col5'>1.5</td>
</tr>
</table>
Each time a delete operation occurs, you can just grab all the existing values and execute a sum or what mathematical operation you use and return the value
function updateTotal(){
var total = 0;
//loop over all table rows
$("#tableData").find("tr").each(function(){
//get all column 3 values and sum them for a total
total += $(this).find("td.col3").text();
}
return total;
}

Categories

Resources