Replaces Value in the first row - javascript

I really need help in my add to cart function. The problem is that when i added product in the shopping cart the second time, it replaces the value in the first. It should be displayed in another row. Please help me. Thanks.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = "<table border='1|1'>";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
html+="</table>";
document.getElementById("demo2").innerHTML = html;
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>

Check below code. I have change it with javascript.
var qtyTotal = 0;
var priceTotal = 0;
var products = [];
function addProduct() {
var productID = document.getElementById("productID").value;
var product_desc = document.getElementById("product_desc").value;
var qty = document.getElementById("quantity").value;
// qtyTotal = qtyTotal + parseInt(qty);
//document.getElementById("qtyTotals").innerHTML=qtyTotal;
var price = document.getElementById("price").value;
var newProduct = {
product_id : null,
product_desc : null,
product_qty : 0,
product_price : 0.00,
};
newProduct.product_id = productID;
newProduct.product_desc = product_desc;
newProduct.product_qty = qty;
newProduct.product_price = price;
products.push(newProduct);
//console.log("New Product " + JSON.stringify(newProduct))
//console.log("Products " + JSON.stringify(products))
var html = "<table border='1|1' >";
html+="<td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Action</td>";
for (var i = 0; i < products.length; i++) {
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td><button type='submit' onClick='deleteProduct(\""+products[i].product_id +"\", this);'/>Delete Item</button> &nbsp <button type='submit' onClick='addCart(\""+products[i].product_id +"\", this);'/>Add to Cart</button></td>";
html+="</tr>";
}
html+="</table>";
document.getElementById("demo").innerHTML = html;
document.getElementById("resetbtn").click()
}
function deleteProduct(product_id, e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
function addCart(product_id){
var html = '';
var ele = document.getElementById("demo2");
if(ele.innerHTML == '')
{
html+="<table id='tblCart' border='1|1'>";
html+="<tr><td>Product ID</td>";
html+="<td>Product Description</td>";
html+="<td>Quantity</td>";
html+="<td>Price</td>";
html+="<td>Total</td>";
html+="<td>Action</td></tr>";
}
for (var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
products[i].product_qty = parseInt(products[i].product_qty) + 1;
html+="<tr>";
html+="<td>"+products[i].product_id+"</td>";
html+="<td>"+products[i].product_desc+"</td>";
html+="<td>"+products[i].product_qty+"</td>";
html+="<td>"+products[i].product_price+"</td>";
html+="<td>"+parseInt(products[i].product_price)*parseInt(products[i].product_qty)+"</td>";
html+="<td><button type='submit' onClick='subtractQuantity(\""+products[i].product_id +"\", this);'/>Subtract Quantity</button></td>";
html+="</tr>";
}
}
if(ele.innerHTML == '')
{
html+= "</table>";
ele.innerHTML = html;
}
else
{
document.getElementById("tblCart").innerHTML += html;
}
}
function subtractQuantity(product_id)
{ alert(product_id);
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id & products[i].product_qty >= 1) {
products[i].product_qty = parseInt(products[i].product_qty) - 1;
}
if (products[i].product_id == 0) {
removeItem(products[i].product_id);
}
console.log("Products " + JSON.stringify(products));
}
}
function removeItem(product_id) {
for(var i = 0; i < products.length; i++) {
if (products[i].product_id == product_id) {
// DO NOT CHANGE THE 1 HERE
products.splice(i, 1);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Pure Javascript</title>
</head>
<body>
<form name="order" id="order">
<table>
<tr>
<td>
<label for="productID">Product ID:</label>
</td>
<td>
<input id="productID" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="product">Product Desc:</label>
</td>
<td>
<input id="product_desc" name="product" type="text" size="28" required/>
</td>
</tr>
<tr>
<td>
<label for="quantity">Quantity:</label>
</td>
<td>
<input id="quantity" name="quantity" width="196px" required/>
</td>
</tr>
<tr>
<td>
<label for="price">Price:</label>
</td>
<td>
<input id="price" name="price" size="28" required/>
</td>
</tr>
</table>
<input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset" />
<input type="button" id="btnAddProduct" onclick="addProduct();" value="Add New Product" >
</form>
<br>
<p id="demo"></p> <br/>
<h2> Shopping Cart </h2>
<p id="demo2"></p>
</body>
</html>

document.getElementById("demo2").innerHTML = html;
Every time, that function is being called, you are changing the innerHTML of of 'demo2' whereas what you need to do is append to it. Use
document.getElementById("demo2").innerHTML += html;
Also, it is not a good idea to use the innerHTML property.It destroys references thus killing eventListeners or similar stuff linked to the object. Hope it helps !

Related

how to find discount from total sum using javascript

I have a table that a user can dynamically add a row as needed. And as you can see underneath the table that is a sum of the last column's value which is dynamically added. I need to add two text boxes above the sum from that one textbox(name as discount) take input(as a number) from user and the second textbox(name as finalsum) display the output as the value(finalsum=sum-discount). and if the user does not give any input value then the discount should be initially zero. and the finalsum should be equal to sum
if you want more info let me know thank you! Any help will be greatly appreciated :)
<html>
<head>
<title>Add/Remove dynamic rows in HTML table</title>
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 4) {
// limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = "row_" + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
var total = mainRow.querySelectorAll("[name=total]")[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1;
// calculate the totale of every total
var sumContainer = document.getElementById("totalOfTotals");
var totalContainers = document.querySelectorAll("[name=total]"),
i;
var sumValue = 0;
for (i = 0; i < totalContainers.length; ++i) {
sumValue += parseInt(totalContainers[i].value);
}
sumContainer.textContent = sumValue;
}
</script>
</head>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id="row_0">
<p>
<td>
<label>Quantity</label>
<input
type="number"
required="required"
name="qty"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="total">Total</label>
<input
type="text"
required="required"
class="small"
name="total"
/>
</td>
</p>
</tr>
</tbody>
</table>
<div>
<tr>
<span>Sum</span>
<span id="totalOfTotals">0</span>
</tr>
</div>
</body>
</html>
Solution Here !!!
<html>
<head>
<title>Add/Remove dynamic rows in HTML table</title>
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 4) {
// limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
row.id = "row_" + rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[0].cells[i].outerHTML;
}
var listitems = row.querySelectorAll("input, select");
for (i = 0; i < listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
}
} else {
alert("Maximum Passenger per ticket is 4.");
}
}
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
var myBox4 = mainRow.querySelectorAll("[name=discount]")[0].value;
var total = mainRow.querySelectorAll("[name=total]")[0];
var myResult1 = myBox1 * myBox3;
total.value = myResult1-myBox4;
// calculate the totale of every total
var sumContainer = document.getElementById("totalOfTotals");
var totalContainers = document.querySelectorAll("[name=total]"),
i;
var sumValue = 0;
for (i = 0; i < totalContainers.length; ++i) {
sumValue += parseInt(totalContainers[i].value);
}
sumContainer.textContent = sumValue;
}
</script>
</head>
<body>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<table id="dataTable" class="form" border="1">
<tbody>
<tr id="row_0">
<p>
<td>
<label>Quantity</label>
<input
type="number"
required="required"
name="qty"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="sel">Price</label>
<select name="sel" id="sel" oninput="calculate('row_0')" required>
<option value="" disabled selected>Choose your option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<label for="discount">Discount</label>
<input
type="text"
required="required"
class="small"
name="discount"
oninput="calculate('row_0')"
/>
</td>
<td>
<label for="total">Total</label>
<input
type="text"
required="required"
class="small"
name="total"
/>
</td>
</p>
</tr>
</tbody>
</table>
<div>
<tr>
<span>Sum</span>
<span id="totalOfTotals">0</span>
</tr>
</div>
</body>
</html>

Access to input values created by javascript function

I have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>

To pass id and name through javascript

The output shown on image
Hi am not much expertise in javascript, In my code I have Add-Items & Delete-Items button which is working fine.First row works fine for total calculation function but rest of rows not working because of that Am not able to assign different names and ids for created row. How I can reuse javascript. Also please let me know how to receive data on submit using POST method or this code and how to find total amount of all rows I inserted at the bottom of table.
Thanks in Advance
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<script type="text/javascript" src="add_rows.js"></script>
<script>
function func()
{
var w = document.getElementById("qty").value;
var x = document.getElementById("price").value;
var z = document.getElementById("total");
z.value = Number(w)*Number(x);
}
</script>
</head>
<body>
<fieldset class="row2">
<legend>Catering Order Details</legend>
<p>
<input type="button" value="Add Items" onClick="addRow('dataTable')" />
<input type="button" value="Remove Items" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" /></td>
<td>
<label>Item</label>
<select size="1" name="Item[]" required="required" >
<?php
echo "<option value=''>---Choose Item---</option>";
$q=mysqli_query($dbConnect1,"SELECT DISTINCT ITEM as Item, ITEM_ID FROM `manage_item`");
while($r=mysqli_fetch_assoc($q))
{
$i=$r['ITEM_ID'];
$n=$r['Item'];
echo "<option value='$i'> $n</option>";
}
?>
</select>
</td>
<td>
<label>Quantity</label>
<input type="text" required="required" name="Qty[]" id="qty" value="">
</td>
<td>
<label>Price/Quantity</label>
<input type="text" required="required" name="Price[]" id="price" value="" onChange="func()">
</td>
<td>
<label>Total</label>
<input type="text" required="required" name="Total[]" id="total" value="">
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</body>
</html>
Here's my script
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 100){
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("Maximum items is 100.");
}
}
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(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot Remove all the Items.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Instead to use IDs you may change them to class names like in:
<input type="text" required="required" name="Qty[]" class="qty" value="" oninput="func(this)">
Because you are using inline events you can:
use input event because the DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
this as parameter to the inline function: it will be the current element
Hence, change your func to:
function func(ele) {
var parentRow = ele.parentNode.parentNode;
var w = parentRow.querySelector('input.qty').value;
var x = parentRow.querySelector('input.price').value;
var z = parentRow.querySelector('input.total');
z.value = Number(w)*Number(x);
}
The this parameter now is the ele, current element. You can now get the parent row and using the classes and querySelector you can find all elements.
The snippet:
function updateGrandTotal() {
var gt = document.querySelector('input.grantotal');
gt.value = 0;
document.querySelectorAll('input.total').forEach(function(ele, idx) {
gt.value = +gt.value + +ele.value;
});
}
function func(ele) {
var parentRow = ele.parentNode.parentNode;
var w = parentRow.querySelector('input.qty').value;
var x = parentRow.querySelector('input.price').value;
var z = parentRow.querySelector('input.total');
z.value = Number(w)*Number(x);
updateGrandTotal();
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length -1;
if(rowCount < 100){
var row = table.insertRow(rowCount + 1);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}else{
alert("Maximum items is 100.");
}
}
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(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot Remove all the Items.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
updateGrandTotal();
}
<fieldset class="row2">
<legend>Catering Order Details</legend>
<p>
<input type="button" value="Add Items" onClick="addRow('dataTable')" />
<input type="button" value="Remove Items" onClick="deleteRow('dataTable')" />
</p>
<table id="dataTable" class="form" border="1">
<thead>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<label>Grand Total</label>
<input type="text" required="required" name="Total[]" class="grantotal" value=""></td>
</tr>
</thead>
<tbody>
<tr>
<p>
<td><input type="checkbox" required="required" name="chk[]" /></td>
<td>
<label>Item</label>
<select size="1" name="Item[]" required="required" >
<option value=''>---Choose Item---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>
<label>Quantity</label>
<input type="text" required="required" name="Qty[]" class="qty" value="" oninput="func(this)">
</td>
<td>
<label>Price/Quantity</label>
<input type="text" required="required" name="Price[]" class="price" value="" oninput="func(this)">
</td>
<td>
<label>Total</label>
<input type="text" required="required" name="Total[]" class="total" value="">
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>

Dynamic HTML form not removing rows - Javascript error

I'm nearing the end of this script and I've noticed an error.
It's possible to add rows to the table, however when I try to remove them it doesn't seem to work. I'm guessing the error is somewhere in my JS. It was working before and then stopped working all of a sudden! Can someone please shed some light on it?
Thanks,
Snelly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
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;
}
}
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 (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>
Here are the code to work:
function deleteRow(tableID) {
debugger;
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].nextElementSibling;
if (chkbox != null && chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
For some reason childNodes[0] is text and childNodes[1] is the input you're looking for.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
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;
}
}
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[1];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>

Automatic start time when a link is clicked [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 5 years ago.
I would like to seek your expertise with regards to the coding below:
this is the layout of my browser, so i divided my page into 2
<FRAMESET rows="5%,*" border=0>
<FRAME SRC="MENU.HTML">
<FRAMESET rows="50%,*">
<FRAME SRC="" NAME=1>
<FRAME SRC="" NAME=2>
</FRAMESET>
</FRAMSET>
below is the code in which i would like to setup the start time automatic where in it will be the same start time in the label.
<html>
<head >
<title>Start and stop</TITLE>
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
<script>function getDateString(){
var myDate = new Date();
return padDatePart(myDate.getMonth() + 1) +
"/" + padDatePart(myDate.getDate()) +
"/" + myDate.getFullYear()+
' ' + padDatePart(myDate.getHours()) +
":" + padDatePart(myDate.getMinutes()) +
":" + padDatePart(myDate.getSeconds());
}
function padDatePart(part){
return ('0'+part).slice(-2);
}
</script>
<script>
function clearFields(formName)
{
var formElements = formName.elements;
for(var i=0;i<formElements.length;i++)
{
var elementType = formElements[i].type;
if('text' == elementType){
formElements[i].value="";
formElements[i].disabled = false;
}
else if('select-one' == elementType){
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
}
else if('select-multiple' == elementType)
{
var multiOptions = formElements[i].options;
for(var j=0;j<multiOptions.length;j++)
{
multiOptions[j].selected = false;
}
}
}
}
</script>
</head>
<form>
<body BGCOLOR=#FFFF99 SCROLL=NO>
<CENTER>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START " >
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled">
| <label id="minutes">00</label>:<label id="seconds">00</label> |
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>
</body>
</html>
</br></br></html>
is it possible to have automatic stop as well when i clicked the stop button?
Move the stuff that needs to be set after the page has rendered to an onload
make sure the table is wrapped in correct form tags
function pad(part) {
return ('0' + part).slice(-2);
}
function getDateString() {
var myDate = new Date();
return pad(myDate.getMonth() + 1) +
"/" + pad(myDate.getDate()) +
"/" + myDate.getFullYear() +
' ' + pad(myDate.getHours()) +
":" + pad(myDate.getMinutes()) +
":" + pad(myDate.getSeconds());
}
function clearFields(formName) {
var formElements = formName.elements;
for (var i = 0; i < formElements.length; i++) {
var elementType = formElements[i].type;
if ('text' == elementType) {
formElements[i].value = "";
formElements[i].disabled = false;
} else if ('select-one' == elementType) {
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
} else if ('select-multiple' == elementType) {
var multiOptions = formElements[i].options;
for (var j = 0; j < multiOptions.length; j++) {
multiOptions[j].selected = false;
}
}
}
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
var minutesLabel, secondsLabel, totalSeconds = 0;
window.onload = function() {
document.getElementById('date').value = Date();
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
setInterval(setTime, 1000);
}
<form>
<table border=0>
<tr>
<td align=center>
<input onclick="this.form.StartTime.value = getDateString();" type="button" class=button value=" START ">
</td>
<td align=center>
<input onclick="this.form.StopTime.value =getDateString();" type="button" class=button value=" STOP ">
</td>
<TD COLSPAN=2 ALIGN=CENTER>
<input type="reset" class=button value=" CLEAR ">
</TD>
</tr>
</table>
<table>
<TR>
<TD colspan=2 align=center>
<input type="text" name="StartTime" size="17" id="date" class=select disabled="disabled"> | <label id="minutes">00</label>:<label id="seconds">00</label> |
<input type="text" name="StopTime" size="17" class=select disabled="disabled">
</TD>
</TR>
</table>
</form>

Categories

Resources