My html data isn't displayed because of my javascript - 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/

Related

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

Auto calculate sum for dynamically add and delete rows - jquery

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);
}

Close previous table row when clicking on another table row

I'm fetching data into the table and on clicking any table row it open a nested colspan inside table row. I want to close previous table row if i click on another table row (Like accordion does )
this is a table body structure
<tbody style="cursor:pointer" v-for="(statement,index) in statements">
<tr #click="statementDetail(index,statement.paper_quality_id.id,statement.paper_brand_id.id,statement.paper_size_id.id,statement.thickness)"
>
<td>{{index+1}}</td>
<td>
{{statement.paper_quality_id.paper_quality}} -
{{statement.paper_size_id.length}} X {{statement.paper_size_id.width}} -
{{statement.paper_brand_id.paper_brand}} -
{{statement.thickness}}
</td>
<td>
<div class="row">
<div
class="col-md-4 text-center"
>{{parseInt((statement.in_total_before - statement.total_out_before)/500)}}</div>
<div
class="col-md-4 text-center"
>{{parseInt((statement.in_total_before - statement.total_out_before)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div
class="col-md-4 text-center"
>{{parseInt((statement.total_sheets_in_range)/500)}}</div>
<div
class="col-md-4 text-center"
>{{parseInt((statement.total_sheets_in_range)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div
class="col-md-4 text-center"
>{{parseInt((statement.total_outward_range)/500)}}</div>
<div
class="col-md-4 text-center"
>{{parseInt((statement.total_outward_range)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div class="col-md-4 text-center">
{{
parseInt((((statement.in_total_before - statement.total_out_before) + (statement.total_sheets_in_range)) - statement.total_outward_range)/500)
}}
</div>
<div class="col-md-4 text-center">
{{
parseInt((((statement.in_total_before - statement.total_out_before) + (statement.total_sheets_in_range)) - statement.total_outward_range)%500)
}}
</div>
</div>
</td>
</tr>
This the nested table it appears when we click on table row
<tr :id="'show_'+index" v-if = "index = indexData" >
<td colspan="6">
<table class="table table-hover">
<tr>
<th>Date</th>
<th>Opening</th>
<th>Inward</th>
<th>Outward</th>
<th>Balance</th>
</tr>
<tr v-for="(_statement,index) in statements_details" >
<td>{{_statement.date}}</td>
<td>
<div class="row">
<div
class="col-md-3 text-center"
>{{parseInt((_statement.opening.total_in - _statement.opening.total_out)/500)}}</div>
<div
class="col-md-3 text-center"
>{{parseInt((_statement.opening.total_in - _statement.opening.total_out)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div class="col-md-3 text-center">{{parseInt((_statement.inward)/500)}}</div>
<div class="col-md-3 text-center">{{parseInt((_statement.inward)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div class="col-md-3 text-center">{{parseInt((_statement.outward)/500)}}</div>
<div class="col-md-3 text-center">{{parseInt((_statement.outward)%500)}}</div>
</div>
</td>
<td>
<div class="row">
<div
class="col-md-3 text-center"
>{{parseInt((_statement.balance.total_in - _statement.balance.total_out)/500)}}</div>
<div
class="col-md-3 text-center"
>{{parseInt((_statement.balance.total_in - _statement.balance.total_out)%500)}}</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
This is my js file
export default {
data() {
return {
statements: '',
users: [],
ledger_name: '',
paper_details: '',
account_list: false,
//statement Objects
id: '',
start_date: '',
end_date: '',
paper_quality_id: '',
paper_size_id: '',
paper_brand_id: '',
thickness: '',
statements_details: '',
stockIDS: '',
indexData: ''
};
},
created() {
this.fetchData();
},
components: {
appInventoryNavigation: InventoryNavBar,
},
methods: {
// Fetching Ledger Account List
fetchData() {
var vm = this;
axios.get('/ledger/')
.then((response) => {
console.log(response)
vm.users = response.data
}).catch((err) => {
console.log(err)
});
},
//Setting LedgerID In Hidden Input Field
setLedgerID_1(id, name) {
this.account_name = id;
this.account_list = false;
this.id = id;
this.ledger_name = name;
},
call() {
this.account_list = true;
},
//Posting LedgeID
PostLedgerID(e) {
e.preventDefault();
const AccountDetail = {
id: this.id,
start_date: this.start_date + ' 00:00:00.957761',
end_date: this.end_date + ' 00:00:00.957761'
}
var vm = this;
axios.post('/Statement/', AccountDetail)
.then((response) => {
console.log(response)
vm.statements = response.data;
}).catch((err) => {
console.log(err)
});
},
//Show Hide Nested Table
statementDetail(rowid, paper_id, brand_id, size_id, thickness) {
this.indexData = rowid;
alert(this.indexData)
const userDetail = {
account_access_key_id: $('#ledger_id').val(),
start_date: this.start_date + ' 00:00:00.957761',
end_date: this.end_date + ' 00:00:00.957761',
paper_quality_id: paper_id,
paper_brand_id: brand_id,
paper_size_id: size_id,
thickness: thickness
}
axios.post('/StatementDetail/', userDetail)
.then((response) => {
$('#show_' + rowid).toggle();
this.statements_details = response.data;
}).catch((err) => {
console.log(err)
});
}
},
};
Change v-show="indexData === index".
And in your method check if rowid is changed and move this.indexData = rowid; after axios request:
statementDetail(rowid, paper_id, brand_id, size_id, thickness) {
if (rowid !== this.indexData){
const userDetail = {
account_access_key_id: $('#ledger_id').val(),
start_date: this.start_date + ' 00:00:00.957761',
end_date: this.end_date + ' 00:00:00.957761',
paper_quality_id: paper_id,
paper_brand_id: brand_id,
paper_size_id: size_id,
thickness: thickness
}
axios.post('/StatementDetail/', userDetail)
.then((response) => {
$('#show_' + rowid).toggle();
this.statements_details = response.data;
}).catch((err) => {
console.log(err)
});
this.indexData = rowid;
}
}
Good luck.

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>

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