Auto calculate sum for dynamically add and delete rows - jquery - javascript

How calculate sum for dynamically add and delete rows, i can create some code but its working only add row, when i click the som wont calculating, I just need auto calculate sum when adding rows and deleting rows.
When i delete rows the total sum not decrese.
Here is fiddle..
FIDDLE HERE
Here is my snippet..
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>

change event doesn't fires when you delete a row. I would suggest to have a separate function that evaluates the total and call it on change as well as on row delete.
see fiddle: https://jsfiddle.net/46fnv9ux/
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
evaluateTotal()
});
$('body').on('change', '[data-action="sumDebit"]', function() {
evaluateTotal();
});
function evaluateTotal() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}

just do the same thing when delete the row which you have done on add.
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>

The delete button click event is not recalculating the total.
The answer by #Devis & Bilal will add all the values to find the sum. Instead you can just subtract the deleted row's value from total.
Modify the delete function as below, to subtract the deleted value from total.
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
counter -= 1
var total = $('#totaldbt').val();
var delVal = $(this).closest("tr").find('input').val();
var val = parseFloat(delVal);
if (!isNaN(val))
total -= val;
$('#totaldbt').val(total);
$(this).closest("tr").remove();
})
;

I moved the calculation to a function calculateTotal and add an event for the delete button to recalculate total when any row is deleted:
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function(){
calculateTotal();
});
$(document).on( 'click', '.ibtnDel', function () {
calculateTotal();
});
function calculateTotal(){
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>
or you can do it in the following way:
$('body').on('change', '[data-action="sumDebit"]', function(){
calculateTotal();
$('#tab_logic').on( 'click', '.ibtnDel', function () {
calculateTotal();
});
});
function calculateTotal(){
var total = 0;
console.log(total);
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}

Related

with jquery I am adding input boxes and table row as shown in pic how can i subtract from total onkeyup when i create a box and put value in it

Here is how I am adding Bank names rows and the which will be added to it
How can i subtract from total row in real time > onkeyup > by creating input using jquery and putting value in it? please help. Actually I want my total sale to be deposited to different banks thats why I want it
<form method="GET" action="savebank.php" class="">
<table class="table table-bordered" id='TextBoxesGroup'>
<tr>
<th>Total Amount</th>
<th id="total" value="<?php echo $tsp; ?>">Rs. <?php echo $tsp; ?></th>
</tr>
<tr id="TextBoxDiv1">
<!-- INPUT BOXES WILL BE HERE-->
</tr>
</table>
<button type="submit" class="btn btn-lg btn-success btn-block" id="ttwo" style="display:none;">Submit</button>
</form>
<!-- Below is jquery -->
<script type="text/javascript">
$(document).ready(function() {
var counter = 2;
$("#addmore").click(function() {
if (counter > 30) {
alert("No more textboxes allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('tr'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<td><input type="text" name="bank[]" required class="form-control" placeholder="Bank Name" id="textbox' + counter + '"></td>' +
'<td><input type="number" name="amnt[]" required class="form-control textboz" placeholder="Amount" id="textbox' + counter + '"></td>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("ttwo").css("display", "block");
$("#remove").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>

My html data isn't displayed because of my javascript

So i started to build a basic website as a practice, and i got until i have a basic html, containing a table of informations, and a form, where you can add to the html through javascript.
My html looks like this
<body>
<hr>
<p class="display-4 text-center">Termék lista</p>
<table class="table">
<thead>
<tr>
<th scope="col">Termék Név</th>
<th scope="col">Termék Azonosító</th>
<th scope="col">Termék Ár</th>
<th scope="col">Termék leírás</th>
<th scope="col">Raktáron</th>
<th scope="col">Törlés</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>mangó</td>
<td>1</td>
<td>499 Ft</td>
<td>Gyümi</td>
<td>Van</td>
<td> <button class="delete btn btn-primary">X</button> </td>
</tr>
</tbody>
</table>
<div class="container mt-5">
<div class="bg-success p-5">
<form id="input-form">
<p class="display-4 text-center">Termékek hozzáadása</p>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputProduct">Termék</label>
<input type="text" class="form-control" id="inputProduct" name="productName">
</div>
<div class="form-group col-md-6">
<label for="inputCode">Termék Azonosító</label>
<input type="number" class="form-control" id="inputCode" name="productCode">
</div>
</div>
<div class="form-group">
<label for="inputPrice">Termék Ára</label>
<input type="number" class="form-control" id="inputPrice" name="productPrice">
</div>
<div class="form-row">
<div class="form-group col-md-8">
<label for="inputDesc">Termék Leírás</label>
<select id="inputDesc" name="inputDesc">
<option value="Gyümölcs">Gyümölcs</option>
<option value="Zöldség">Zöldség</option>
</select> </div>
<div class="form-group col-md-4">
<label for="inputSupply">Raktáron </label>
<select id="inputSupply" name="productSupply">
<option value="Van">Van</option>
<option value="Nincs">Nincs</option>
</select>
</div>
</div>
<button id="submit-button" type="submit" class="btn btn-primary">Hozzáadás</button>
</form>
</div>
</div>
And this is my javascript code so far:
var products = [
{
productName:"körte",
productCode: 2,
productPrice: 30,
productDesc: "Gyümi",
productSupply: "Nincs",
productId: 1
},
{
productName: "répa",
productCode: 3,
productPrice: 20,
productDesc: "Gyümi",
productSupply: "Van",
productId: 5
},
{
productName: "paradicsom",
productCode: 4,
productPrice: 50,
productDesc: "Gyümi",
productSupply: "Nincs",
productId: 6
}
]
var table = '<tbody>'
for( i = 0; i < products.length; i++){
table += `<tr>`;
table += `<td>` + products[i].productName + `</td>`;
table += `<td>` + products[i].productCode + `</td>`;
table += `<td>` + products[i].productPrice + `</td>`;
table += `<td>` + products[i].productDesc + `</td>`;
table += `<td>` + products[i].productSupply + `</td>`;
table += `<td> <button class="delete btn btn-primary" id="${products[i].productId}">X</button> </td>`
table += '</tbody>';
}
document.getElementById('tbody').innerHTML = table;
const tBody = document.getElementById("tbody")
tBody.addEventListener("click", function(x){
console.log("remove from tomb");
console.log(x.target);
console.log("gomb id: " + x.target.id);
for (let i = 0; i < products.length; i++) {
console.log("tomb i id: " + products[i].productId);
if (x.target.id == products[i].productId) {
console.log("removed");
products.splice(i, 1);
}
}
if(x.target.classList.contains("delete")) {
x.target.parentElement.parentElement.remove();
}
console.log(products);
})
const productInput = document.getElementById("inputProduct");
const codeInput = document.getElementById("inputCode");
const priceInput = document.getElementById("inputPrice");
const descInput = document.getElementById("inputDesc");
const supplyInput = document.getElementById("inputSupply");
const submitButton = document.getElementById("submit-button");
const addProduct = (ev) => {
ev.preventDefault();
let newProduct ={
productName: document.getElementById("inputProduct").value,
productCode: document.getElementById("inputCode").value,
productPrice: document.getElementById("inputPrice").value,
productDesc: document.getElementById("inputDesc").value,
productSupply: document.getElementById("inputSupply").value,
productId: Date.now()
}
let newRow = document.createElement("tr");
newRow.innerHTML += `
<td>${newProduct.productName}</td>
<td>${newProduct.productCode}</td>
<td>${newProduct.productPrice}</td>
<td>${newProduct.productDesc}</td>
<td>${newProduct.productSupply}</td>
<td> <button class="delete btn btn-primary" id="${newProduct.productId}">X</button> </td>`
tBody.appendChild(newRow);
products.push(newProduct);
document.querySelector('form').reset();
console.warn("added", {products});
}
document.addEventListener("DOMContentLoaded", ()=>{
submitButton.addEventListener("click", addProduct)
})
The problem is, as you can see i already have a product in the html, but i think my javascript for function, which displays the data from the .js overwrited the data from the html, thus displaying only the 3 products from javascript var = products. How can i have both the html data and the javascript data displayed simultaneously, so i have all 4 products when i open my .html?
Just modify this line as following. Hope to help, my friend :))
document.getElementById('tbody').innerHTML += table;
Here is the output:
http://jsfiddle.net/3zd0y64n/

sum td value in table with jquery

I have a table in my program, which adds the values to that row
How can I add the third value of each row?
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
I want to add items within the item's price and show it somewhere for example a div tag or span tag.
In this example, the third child of each scroll row should be added together and sum them together
Updated code by writing 'sum' logic in separate function.
function calculateSum() {
//Calculate sum of price
var sum = 0;
$('.table tbody tr').each(function() {
var item_price = parseInt($(this).find('td:nth-child(3)').html());
//Check for NaN & add.
sum += item_price?item_price:0;
});
//Display to div
$("#total").text(sum);
}
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
calculateSum(); //Perform sum after removing row.
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
calculateSum(); //Perform sum after adding row.
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="total"></div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
below code help you to add logic for sum.
$(document).ready(function() {
var totle = 0;
$(".add-row").click(function() {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
totle += parseInt(item_price);
});
$("table").on("click", "#del", function() {
$("table tbody").find('tr td').each(function() {
$("table").on("click", "#del", function() {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function() {
var ids = [];
$('.table tbody tr').each(function() {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
alert("Totle price is : " + totle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can create a div with totalprice and then please add some jQuery code as mentioned below.
var totalprice = item_price;
var currentprice = $("#totalprice").text();
totalprice = (parseInt(currentprice) + parseInt(item_price)) ;
$("#totalprice").html(totalprice);
Add it in add button.
$(".add-row").click(function () {
var packageid = $('#pack').find(':selected').attr('data-id');
var itemid = $('#itemname').find(':selected').attr('item-id');
var itemname = $("#itemname").val();
var item_price = $("#item_price").val();
var packs = $("#pack").val();
var markup = "<tr><td data-id=" + packageid + ">" + packs + "<td item-id=" + itemid + ">" + itemname + "</td><td class='price'>" + item_price + "</td><td><button class='btn btn-danger' id='del'>Delete</button></td></tr>";
$("table tbody").append(markup);
var totalprice = item_price;
var currentprice = $("#totalprice").text();
totalprice = (parseInt(currentprice) + parseInt(item_price)) ;
$("#totalprice").html(totalprice);
});
$("table").on("click", "#del", function () {
$("table tbody").find('tr td').each(function () {
$("table").on("click", "#del", function () {
$(this).parents("tr").remove();
})
});
});
$('.add-row').click(function () {
var ids = [];
$('.table tbody tr').each(function () {
ids.push({
packageid: $(this).find('td:nth-child(1)').attr('data-id'),
itemid: $(this).find('td:nth-child(2)').attr('item-id'),
item_price: $(this).find('td:nth-child(3)').html(),
});
});
$('#demo').val(JSON.stringify(ids));
});
<form>
<div class="col-md-3">
<select class="form-control" id="pack" required>
<option data-id="1" value="test">test</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" id="itemname">
<option item-id="1" value="test">example</option>
</select>
</div>
<div class="col-md-3">
<input type="number" class="form-control" id="item_price" placeholder="Price">
</div>
<div class="col-md-3">
<button type="button" class="add-row btn btn-success cusb btn-anim"><i class="fas fa-plus"></i><span class="btn-text">Add Item</span></button>
</div>
<div class="col-md-3">
<b>Total Price is : </b><span id = "totalprice">0</span>
</div>
</form>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Package Name</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>

JavaScript Total Cost after deleting Item

I have foreached some items that I sell :
<?php foreach ($selectedItems as $item): ?>
<tr class="product" data-price="<?= $item->price ?>">
<th class="items"><?= $item->name ?></th>
<th id="price" class="items middle-th "> <!-- the 3rd column -->
<div >
<button type="button" class="sub" title="If u want less quantity">-</button>
<input class="quantityTxt quantity " id="quantity" name="quantity[]" type="text" value="1" onchange="quantityChange(this)" >
<button type="button" class="add" title="If u want more quantity" >+</button>
</div>
</th>
<th>
<span class="productTotal"></span>
</th>
<th id="price" class="items">
<button class="remove_field" data-value="<?= $item->price ?>" title="Click to delete product" >
<div class="glyphicon glyphicon-trash" ></div>
</button>
</th>
</tr>
<?php endforeach; ?>
</table>
<div class="row-fluid well">
<strong id="total"> Total: € <span id="sum"> </span> </strong></div>
<div class="payment">
I set onClick to delete the row after the button is pressed so to delete the rows so I need when I delete the row , to minus the total cost of the product form the total sum . Later is my Script Code where I have all of the things ,but I left only to minus from Total the Cost of the deleted row .
$('table').on('click', 'button.remove_field', function () {
$(this).closest('tr').remove();
var id = $(this).attr('data-value');
console.log(id);
});
$('.add').click(function () {
var target = $('.quantity', this.parentNode)[0];
target.value = +target.value + 1;
updateTotal();
});
$('.sub').click(function () {
var target = $('.quantity', this.parentNode)[0];
if (target.value > 1) {
target.value = +target.value - 1;
}
updateTotal();
});
var updateTotal = function () {
var sum = 0;
//Add each product price to total
$(".product").each(function () {
var price = $(this).data('price');
var quantity = $('.quantityTxt', this).val();
//Total for one product
var subtotal = price * quantity;
//Round to 2 decimal places.
subtotal = subtotal.toFixed(2);
//Display subtotal in HTML element
$('.productTotal', this).html(subtotal);
});
// total
$('.productTotal').each(function () {
sum += Number($(this).html());
});
$('#sum').html(sum.toFixed(2));
};
//Update total when quantity changes
$(".product").keyup(function () {
updateTotal();
});
//Update totals when page first loads
updateTotal();
// set this from local
$('span.productTotal').each(function () {
$(this).before("€");
});
// unit price
$('.product').each(function () {
var $price = $(this).parents("div").data('price');
$(this).before($price);
});

how to find total value from adding value in html and value in dynamic form with javascript?

i have problem to find total_penjualan value.
i use dynamic form here. i want add all total's value in dynamic form with biayalainlain's value. i think the problem is in var ttl2 = document.getElementById(totalid).value; how to get id in additem() to put in prosestotal()?
this is my html and javascript code:
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('type', 'number');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'harga form-control');
/*harga_input.setAttribute('onkeyup', 'sum();');*/
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('type', 'number');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'jumlah form-control');
jumlah_input.setAttribute('autocomplete', 'off');
/*jumlah_input.setAttribute('onkeyup', 'sum();');*/
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'total form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(total_input).on('keyup',function(){
prosestotal(totalid,total,biayalain)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
}
function prosestotal(){
var ttl = document.getElementById('total').value;
var ttl2 = document.getElementById(totalid).value;
var biayalain = document.getElementById('biayalain').value;
var hsl = parseInt(ttl) + parseInt(ttl2) + parseInt(biayalain);
if (!isNaN(hsl)) {
document.getElementById('total_penjualan').value = hsl;
}
}
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input type="number" id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input type="number" id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value="" onkeyup="prosestotal();" /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="tambah" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
<!-- Baris biaya lain-lain -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Biaya Lain-lain :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="biayalain" type="number" autocomplete="off" class="form-control" name="biaya_lainlain" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
<!-- baris biaya dan lain-lain end -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Total Penjualan :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="total_penjualan" type="number" readonly autocomplete="off" class="form-control" name="total_penjualan" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
any help is appreciated

Categories

Resources