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>
Related
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);
}
I am unable to send the value of javascript variale 'userResults' to .html.
I want to display the contents of the form in tabular form.
Can you tell me a workaround for this?
This is in index.html
<form onSubmit="App.retrieveTransaction();" class="form2">
<h1 class="text-center">Retrieve transactions</h1>
<div class="form-group">
<label for="enterregnoselect">Reg No:</label><input id ="enterregnoselect" class="form-control" type ="text" required/>
</div>
<button type="submit" class="btn btn-primary" >Retrieve</button>
<hr />
<table class="table">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">Name</th>
<th scope="col">Item</th>
<th scope="col">Credit</th>
<th scope="col">Debit</th>
<th scope="col">Price</th>
<th scope="col">Qty</th>
</tr>
</thead>
<tbody id="userResults">
</tbody>
</table>
<hr/>
</form>
This is the retrieveTransaction function in app.js called on submitting the form in index.html
retrieveTransaction: function() {
var transactionInstance;
var enteredregno = $('#enterregnoselect').val();
// var enteredregno = "0015/55";
App.contracts.Payment.deployed().then(function(instance) {
transactionInstance = instance;
return transactionInstance.transactionCount();
}).then(function(transactionCount) {
var userResults = $("#userResults");
userResults.empty();
for (var i = 1; i <= transactionCount; i++) {
transactionInstance.transactions(i).then(function(transaction) {
var date = transaction[0];
var regno = transaction[1];
var name = transaction[2];
var item = transaction[3];
var credit = transaction[4];
var debit = transaction[5];
var price = transaction[6];
var qty = transaction[7];
if(enteredregno == regno) {
var userTemplate = "<tr><th>" + date + "</th><td>" + name + "</td><td>" + item + "</td></tr>" + credit + "</th><td>" + debit + "</td><td>" + price + "</td></tr>" + qty + "</td></tr>";
userResults.append(userTemplate);
}
});
}
});
I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>
I have problem getting the value of the replace new table row, I will let you show the codes for the replacing new table row.
The is the Table B, Where this code use for replacing new table row to the Table A
$('#edit_chainingBuild').on('click','tr.clickable-row',function(e){
$('table#edit_chainingBuild tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_will_update = $(this).find('.data-attribute-chain-id').attr('data-attribute-chain-id');
$('.id_to_update_chain').val(find_each_id_will_update);
var find_each_id_condiments = $(this).find('.data-attribute-chain-id').attr('data-attribute-condiments-section-id');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var condiment_section_name = stringify['condiment_section_name'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#edit_table_chaining_condiments').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td>"+condiment_section_name +"</td><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
$("table#edit_table_chaining_condiments tr").click(function(e){
var tableBhtml = $(this).closest('tr').html();
var condiments_name = $(this).closest("tr").find(".edit_condimentsScreenNameClicked").text();
var condimentsScreenPriced = $(this).closest("tr").find(".edit_condimentsScreenPriced").text();
// var input = '<input type="number" id="qty" name="qty" class="form-control changeQuantity" value="1" min="1">';
var id_to_edit_build = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").html('');
var id_to_edit_builders = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").replaceWith("<tr data-attribute-chain-id=" + id_to_edit_build + " class='clickable-row'><td class='new_condiments_name'>"+condiments_name+"</td><td>"+condimentsScreenPriced+"</td><td style='display:none;' data-attribute-chain-id="+id_to_edit_builders +" class='data-attribute-chain-id'>"+id_to_edit_builders+"</td></tr>");
$('#EditcondimentsBuilderModal').modal('hide');
});
},
error:function(response){
console.log(response);
}
});
$('#EditcondimentsBuilderModal').modal('show');
});
Looking forward if the table row already replace, I want to get the value of the class of new_condiments_name. So I create a variable to find the class of new_condiments_name. It look like this.
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
So now when I try alert the variable new_condiments_name using the click function it shows null only.
$('.edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
My Html Table:
<div class="modal-body">
<div class="container">
<div class="header" style="text-align: center;">
<br>
<h3 style="color:#007BFF;">Build Your Chain Button</h3>
<label>This button will be served as customers menu.</label><br>
<i class="fab fa-creative-commons-remix" style="font-size:70px;"></i>
<br><br>
<input type="hidden" value="" class="edit_hidden_noun_id" name="">
<table class="table table-hover" id="edit_chainingBuild">
<thead>
<tr style="font-size: 15px;">
<!-- <th scope="col">Qty</th> -->
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px;">
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="edit_build_success_insert btn btn-primary">Build Done</button>
</div>
I have here the image to proof that the value that i get always null.
$('table .edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
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