Sum column in dynamic table - javascript

I have a dynamic table which calculates the a total column at the end of each row depending on input values but I cannot seem to get the total of this row?
I create my table with:
function calc() {
var td = document.querySelectorAll('#item_table > tr > td:last-child');
var stotal = [].reduce.call(td, function(a, b) {
return a + parseInt(b.innerText);
}, 0);
document.getElementById('sub_total').innerText = stotal;
}
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="number" min="0" value="0" name="item_name[]" oninput="calc();calcSub()" class="form-control item_name" size="16" /></td>';
html += '<td><input type="number" min="0" value="0" name="item_quantity[]" oninput="calc()" class="form-control item_quantity" /></td>';
html += '<td><input type="number" min="0" value="0" name="item_unit[]" oninput="calc()" class="form-control item_unit" /></td>';
//NEW ONES!!!!!!!!!!!!!!!
html += '<td><select name="item_glass[]" oninput="calc()" class="form-control item_glass"><option>Select Glass Type</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><select name="item_splash[]" oninput="calc()" class="form-control item_splash"><option value="0">Select Splash</option><?php echo fill_unit_select_box3($connect); ?></select></td>';
html += '<td><input type="text" value="-" name="item_colour[]" oninput="calc()" class="form-control item_colour" /></td>';
html += '<td><input type="number" min="0" value="0" oninput="calc()" name="item_HQuan[]" class="form-control item_HQuan" /></td>';
html += '<td><select name="item_HDiam[]" oninput="calc()" class="form-control item_HDiam"><option value="0">Select Hole Diameter</option><?php echo fill_unit_select_box2($connect); ?></select></td>';
html += '<td><input type="number" min="0" value="0" oninput="calc()" name="item_CQuan[]" class="form-control item_CQuan" /></td>';
//Total
html += '<td><input type="text" value="0.0" name="item_Total[]" id="item_Total[]" class="form-control item_Total" disabled/></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove">Delete Item<span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="item_table">
<tr id="titles">
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Glass Type</th>
<th>Sparkle or Glaze</th>
<th>Colour Code</th>
<th>Hole Quantity</th>
<th>Hole Diameter</th>
<th>Cut-out Quantity</th>
<th>Item cost £ (excl. Vat)</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span>Add Item</button></th>
</tr>
</table>
<div class="form-group">
<label for="job_ref">Sub Total</label>
<input type="text" id="sub_total" class="form-control sub_total" name="sub_total" placeholder="0" value="0" readonly/>
</div>
Another thing tried but always equal to 0 regardless of the input:
function calcSub(){
var cls = document.getElementById("item_Total[]").getElementsByTagName("td");
var sum = 0;
for (var i = 0; i < cls.length; i++){
if(cls[i].className == "countable"){
sum += isNaN(cls[i].value) ? 0 : parseInt(cls[i].value);
}
}
document.getElementById('sub_total').value = sum;
};
Is their anyway to do this I cant figure it out?

function calcSub(){
var totalPrice = 0;
$(".item_Total").each(function(){
totalPrice += parseInt($(this).val());
$(".sub_total").val(totalPrice);
});
Answer driven from post: How to sum values from table column and update when remove/add new row

Try something like this code
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="number" min="0" value="0" name="item_name[]" class="form-control item_name" size="16" /></td>';
html += '<td><input type="number" min="0" value="0" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><input type="number" min="0" value="0" name="item_unit[]" class="form-control item_unit" /></td>';
//NEW ONES!!!!!!!!!!!!!!!
html += '<td><select name="item_glass[]" class="form-control item_glass"><option>Select Glass Type</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><select name="item_splash[]" class="form-control item_splash"><option value="0">Select Splash</option><?php echo fill_unit_select_box3($connect); ?></select></td>';
html += '<td><input type="text" value="-" name="item_colour[]" class="form-control item_colour" /></td>';
html += '<td><input type="number" min="0" value="0" name="item_HQuan[]" class="form-control item_HQuan" /></td>';
html += '<td><select name="item_HDiam[]" class="form-control item_HDiam"><option value="0">Select Hole Diameter</option><?php echo fill_unit_select_box2($connect); ?></select></td>';
html += '<td><input type="number" min="0" value="0" name="item_CQuan[]" class="form-control item_CQuan" /></td>';
//Total
html += '<td><input type="text" value="0.0" name="item_Total[]" id="item_Total[]" class="form-control item_Total" disabled/></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove">Delete Item<span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('change', 'input', function() {
$("table tr").each(function(ind, el) {
var sum = 0; $(this).find("input:not(:last)").each(function(indx, ele) {
sum += $(ele).val();
});
$(this).find("input").last().val(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="item_table">
<tr id="titles">
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Glass Type</th>
<th>Sparkle or Glaze</th>
<th>Colour Code</th>
<th>Hole Quantity</th>
<th>Hole Diameter</th>
<th>Cut-out Quantity</th>
<th>Item cost £ (excl. Vat)</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span>Add Item</button></th>
</tr>
</table>
<div class="form-group">
<label for="job_ref">Sub Total</label>
<input type="text" id="sub_total" class="form-control sub_total" name="sub_total" placeholder="0" value="0" readonly/>
</div>
But consider these:
1-create a class for columns you want to be calculated and modify its jquery selector.
2-ensure the input values always are numeric, then convert them into Number.
3-for the Sub Total insert special jquery code you want. (I did not add that, because I don't know how exactly calculate its value)

Related

Pagination not working?? - jQuery or Javascript

I just create dynamic table with Pagination but the pagination is not working with that table..
Im using bootstrap table with jquery.
I want to allow 5 rows only display, remaining rows are paginate.
Here is my fiddle
FIDDLE HERE..
How to paginate when dynamically add rows.
Here is a example code.
$(document).ready(function() {
$("#add_Row").on("click", function() {
var counter = 0;
var idVal = $('#tab_logic tr:last').find('td:first').html();
var matches = idVal.match(/\d+/g);
if (matches != null) {
counter = Number(matches) + counter + 1;
}
// alert(counter);
var newRow = $("<tr>");
var cols = "";
cols += '<td class="cashpay_led" style="display:none;"><input type="number" class="form-control" id="table_ledger' + counter + '" name="ledgerno" placeholder="ledger number"/></td>';
cols += '<td><input type="number" class="form-control sel_text" id="cashAcctcode' + counter + '" name="acctcode" placeholder="Account code"/></td>';
cols += '<td><select class="form-control sel_sel status" id="accountName' + counter + '" name="accountName"><option>Choose A/c Name</option></select></td>'
cols += '<td><textarea class="form-control pname required price" name="narr" placeholder="Enter your text here" id="acc_narrat' + counter + '" maxlength="200"/></textarea></td>';
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><input type="number" class="form-control comment" id="crditCash' + counter + '" data-action="sumCredit" name="credit" placeholder="Credit amount" tabindex="-1" readonly/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
});
// pagination
$(function() {
$('#tab_logic').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': false,
'autoWidth': false,
'pageLength': 5
})
});
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.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">
<tbody>
<tr id="fst_row">
<td style="display: none;">
<input type="number" id="staticLedger" placeholder='Ledger Number' for="staticLedger" name="ledgerno" class="form-control" />
</td>
<td style="display: none;">
<input type="text" id="tdsrow" placeholder='Ledger Number' name="tdsrow" value="Y" th:value="Y" class="form-control" />
</td>
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' for="acctcode" name="acctcode" class="form-control sel_text" />
</td>
<td>
<select class="form-control sel_sel" id="payacc" name="actname" for="actname">
</select>
</td>
<td>
<textarea class="form-control pname required" id="pay_narrat" name="narr" for="narr" placeholder="Enter your text here"></textarea>
</td>
<td>
<input type="text" id="paydeb" name="debit" for="debit" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" name="credit" for="credit" placeholder='Credit Amount' data-action="sumCredit" class="form-control" tabindex="-1" readonly />
</td>
<td><button type="button" class="adRow" style="width:70%; cursor: not-allowed;">x</button></a>
</td>
</tr>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
What im doing wrong?
How to set paginate in dynamically add rows.
Thank you
There are some mistake in your code snippet :
1.In table th tags are less than td , which you are appending
2.Calling Datatable before Jquery define
If you want to set paginate in dynamically add rows, then you have to destroy it and reinitialise it.
I remove some hidden properties just to check,you can hide them adding class
"columnDefs": [{ "class": "hide", "targets": 3 } ]
OR
"columnDefs": [{"targets": [ 2 ],"visible": false}]
Hope this will help you
$(document).ready(function() {
$("#add_Row").on("click", function() {
var counter = 0,setValCashVal =0;
var idVal = $('#tab_logic tr:last').find('td:first').html();
var matches = idVal.match(/\d+/g);
if (matches != null) {
counter = Number(matches) + counter + 1;
}
// alert(counter);
if ($.fn.DataTable.isDataTable('#tab_logic')) {
$('#tab_logic').DataTable().destroy()}
var newRow = $("<tr>");
var cols = "";
cols += '<td class="cashpay_led" ><input type="number" class="form-control" id="table_ledger' + counter + '" name="ledgerno" placeholder="ledger number"/></td>';
cols += '<td> <input type="text" id="tdsrow' + counter + '" placeholder="Ledger Number" name="tdsrow" value="Y" th:value="Y" class="form-control" /></td>';
cols += '<td><input type="number" class="form-control sel_text" id="cashAcctcode' + counter + '" name="acctcode" placeholder="Account code"/></td>';
cols += '<td><select class="form-control sel_sel status" id="accountName' + counter + '" name="accountName"><option>Choose A/c Name</option></select></td>'
cols += '<td><textarea class="form-control pname required price" name="narr" placeholder="Enter your text here" id="acc_narrat' + counter + '" maxlength="200"/></textarea></td>';
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><input type="number" class="form-control comment" id="crditCash' + counter + '" data-action="sumCredit" name="credit" placeholder="Credit amount" tabindex="-1" readonly/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
// setValCashVal('accountName'.concat(counter));
//bindScript();
$('#tab_logic').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': false,
'autoWidth': false,
'pageLength': 5
})
counter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="
https://cdn.datatables.net/1.10.20/js/dataTables.jqueryui.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" href=" https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/scroller/2.0.1/css/scroller.jqueryui.min.css">
</head>
<body>
<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>
<tr style="background-color: #680779; color: #fff;">
<th></th><th></th>
<th class="text-center">
Account Code
</th>
<th class="text-center">
A/c Name*
</th>
<th class="text-center">
Narration*
</th>
<th class="text-center">
Debit*
</th>
<th class="text-center">
Credit
</th>
<th class="text-center">
Action
</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td >
<input type="number" id="staticLedger" placeholder='Ledger Number' for="staticLedger" name="ledgerno" class="form-control" />
</td>
<td >
<input type="text" id="tdsrow" placeholder='Ledger Number' name="tdsrow" value="Y" th:value="Y" class="form-control" />
</td>
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' for="acctcode" name="acctcode" class="form-control sel_text" />
</td>
<td>
<select class="form-control sel_sel" id="payacc" name="actname" for="actname"><option>Choose A/c Name</option>
</select>
</td>
<td>
<textarea class="form-control pname required" id="pay_narrat" name="narr" for="narr" placeholder="Enter your text here"></textarea>
</td>
<td>
<input type="text" id="paydeb" name="debit" for="debit" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" name="credit" for="credit" placeholder='Credit Amount' data-action="sumCredit" class="form-control" tabindex="-1" readonly />
</td>
<td><button type="button" class="adRow" style="width:70%; cursor: not-allowed;">x</button>
</td>
</tr>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div></body></html>

dynamically add value summation in row and colum

using this code i can already calculate two value in row now I am trying to sum column values below local column field all column value with this,
<table class="table order-list turf" id="turf">
<tr>
<td>Items</td>
<td>Local</td>
<td>Foreign</td>
<td>Total</td>
</tr>
<tr>
<td class="col-sm-3"><input type="text" name="" value="item1"></td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value1[]" class="calculated_value"/></td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value2[]" class="form-control calculated_value" />
</td>
<td class="col-sm-3 total">
<input type="text" name="total[]" class="form-control total" id="total" readonly="" />
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
<input type="button" class="btn btn-sm btn-success " id="addrow" value="Add" />
</td>
</tr>
<tr class="grand-total persist">
<td>Total Investment</td>
<td id="local_total"><input type="text" readonly="" name=""></td>
<td id="foreign_total"><input type="text" readonly="" name=""></td>
<td id="total_total"><input type="text" readonly="" name=""></td>
</tr>
</table>
var counter = 1;
$("body").on("input", ".calculated_value", function() {
var parent_row = $(this).closest('tr');
var totalincome = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find(".total").val(totalincome);
Demo
I hope this is what you need. Code could be refactored but I think you can do it yourself.
$(document).ready(function() {
var counter = 1;
$("body").on("input", ".calculated_value", function() {
calculate(this);
});
function calculate(elm) {
var parent_row = $(elm).closest('tr');
var elTotalIncome = $("#local_milion_grand_total").find("input");
var elTotalForeign = $("#foreign_milion_grand_total").find("input");
var elTotal = $('#total_milion_grand_total').find("input");
var totalincome = 0;
var totalLocal = 0;
var totalForeign = 0;
var total = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find('.total').val(totalincome);
for (i = 0; i < $("tbody tr").length; i++) {
let elCol = $($("tbody tr")[i]).find("td input");
let tmp = parseInt(elCol[1].value);
let tmp2 = parseInt(elCol[2].value);
let tmp3 = parseInt(elCol[3].value);
if (isNaN(tmp)) tmp = 0;
if (isNaN(tmp2)) tmp2 = 0;
if (isNaN(tmp3)) tmp3 = 0;
totalLocal += tmp;
totalForeign += tmp2;
total += tmp3;
}
elTotal.val(total);
elTotalIncome.val(totalLocal);
elTotalForeign.val(totalForeign);
}
//add new row button
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" value="Item ' + counter + '"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="value1[]"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>';
cols += '<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
if (counter == 1) return;
$(this).closest("tr").remove();
counter -= 1
calculate(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table order-list turf" id="turf">
<thead>
<tr>
<td>Items</td>
<td>Local(Milion Taka/Milion US$)</td>
<td>Foreign(Milion Taka/Milion US$)</td>
<td>Total(Milion Taka/Milion US$)</td>
<td> <input type="button" class="btn btn-sm btn-success " id="addrow" value="Add" /></td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-3">
<input type="text" name="" value="item1">
</td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value1[]" class="form-control calculated_value_row calculated_value" />
</td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value2[]" class="form-control calculated_value_row calculated_value" />
</td>
<td class="col-sm-3 total">
<input type="text" name="total[]" class="form-control total" id="total" readonly="" />
</td>
<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>
</tr>
</tbody>
<tfoot>
<tr class="grand-total persist">
<td>Total Investment</td>
<td id="local_milion_grand_total"><input type="text" class="form-control local_milion_grand_total" readonly="" name=""></td>
<td id="foreign_milion_grand_total"><input type="text" class="form-control" readonly="" name=""></td>
<td id="total_milion_grand_total"><input type="text" class="form-control" readonly="" name=""></td>
</tr>
</tfoot>
</table>

Passing multiple parameters with serialize jQuery in PHP

I have a problem with a serialized form. I need to pass multiple rows for creating an invoice, but it passes just the first row.
This is a form:
<form action="" id="generate_invoice" method="POST">
<td><input type="number" class="form-control n_invoice" name="n_invoice[]"></td>
<td><input type="date" class="form-control data" name="data[]"></td>
<td><input type="text" class="form-control description" name="description[]"></td>
<td><input type="number" class="form-control price" name="price[]" step=any></td>
<td><input type="number" class="form-control vat" name="vat[]">
</form>
This is a function which adds new rows:
function addrow_invoice() {
var i = $('#invoiceTable tr').length;
var tr = '<tr>'+
'<td><input type="checkbox" class="case"/></td>'+
'<td></td>'+
'<td></td>'+
'<td><input type="text" class="form-control description" name="description[]"></td>'+
'<td><input type="number" class="form-control price" name="price[]"></td>'+
'<td><input type="number" class="form-control vat" name="vat[]"></td>'+
'</tr>';
$('table#invoiceTable').append(tr);
i++;
};
And this is a test:
for($i = 0; $i<count($_POST['description']); $i++)
{
echo "{$_POST['description'][$i]}";
echo "<br>";
}
The issue is because your HTML is invalid. The form needs to wrap the table element, not be inside it. Because the HTML is invalid, the location of the form is moved so that it's not wrapping your input elements, hence nothing gets serialised.
Your HTML needs to be changed to this:
<form action="" id="generate_invoice" method="POST">
<table id="invoiceTable">
<tr>
<td><input type="number" class="form-control n_invoice" name="n_invoice[]"></td>
<td><input type="date" class="form-control data" name="data[]"></td>
<td><input type="text" class="form-control description" name="description[]"></td>
<td><input type="number" class="form-control price" name="price[]" step=any></td>
<td><input type="number" class="form-control vat" name="vat[]">
</tr>
<!-- additional rows appended here... -->
</table>
</form>

Row count in dynamically generated table using JQuery

I've a table with header and footer and a default row already created. When I add more rows dynamically I don't get the exact row count. It always returns the correct row count if I add them before.
Below is the code I've written -
<table id="empTable" class="table table-responsive table-striped table-bordered">
<thead>`enter code here`
<tr>
<td>Name of Employee</td>
<td>Father's Name/Husband's Name</td>
<td>Basic</td>
<td>Total attendance</td>
<td>Clear</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
<tr>
<td><input id="emp_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input id="father_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
<script>
//function to add/remove rows
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
//function to return value of Dynamic content
function GetDynamicTextBox(value) {
return '<td><input name="DynamicTextBox" type="text" value="" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="text" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>'
}
</script>
And I'm using this line to return row count but it's not working -
var rowCount = document.getElementById("TextBoxContainer").rows.length;
$('#btnSave').on('click', function() {
alert(rowCount);
})
I've tried all the solutions from stackoverflow but not getting why it's not working for dynamic rows whereas same code I saw in a fiddle working.
Please help.
Because you create new rows on the fly you need to move this line:
var rowCount = document.getElementById("TextBoxContainer").rows.length;
inside:
$('#btnSave').on('click', function() {
And as per #charlietf comment I would suggest to change the row count in:
var rowCount = $("#TextBoxContainer tr").length;
//function to return value of Dynamic content
function GetDynamicTextBox(value) {
return '<td><input name="DynamicTextBox" type="text" value="" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="text" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>';
}
$(function () {
$('#btnSave').on('click', function() {
var rowCount = $("#TextBoxContainer tr").length;
console.log('Rows: ' + rowCount);
})
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="empTable" class="table table-responsive table-striped table-bordered">
<thead>`enter code here`
<tr>
<td>Name of Employee</td>
<td>Father's Name/Husband's Name</td>
<td>Basic</td>
<td>Total attendance</td>
<td>Clear</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
<tr>
<td><input id="emp_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input id="father_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button>
<button id="btnSave" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="ASavee controls"><i class="glyphicon glyphicon-plus-sign"></i> Save </button></th>
</tr>
</tfoot>
</table>

Update total on deleting the row in table

I have a html table where total amount is not getting updated on entering new values and also not getting updated. It only shows NaN.
here is the javascript code:
function totamt(){
var table = document.getElementById("stock");
var total = document.getElementById("total");
var tot = 0;
for(var i=0;i<table.rows.length;i++){
var currentRow = table.rows[i];
tot = tot + parseInt(currentRow.cells[currentRow.cells.length - 1].innerHTML);
}
alert(tot.toString());
document.getElementById('total').innerHTML = tot.toString();
}
$('body').delegate('.remove','click',function(){
$(this).parent().parent().remove();
totalamt();
});
Interactive Snippet
$(function() {
$('#add').click(function() {
addnewrow();
});
$('body').delegate('.remove', 'click', function() {
$(this).parent().parent().remove();
totalamt();
$('.details').delegate('.qty,.price', 'keyup', function() {
var tr = $(this).parent().parent();
var q = tr.find('.qty').val();
var p = tr.find('.price').val();
var a = (q * p);
tr.find('.amt').val(a);
totamt();
});
function totamt() {
var table = document.getElementById("stock");
var total = document.getElementById("total");
var tot = 0;
for (var i = 0; i < table.rows.length; i++) {
var currentRow = table.rows[i];
tot = tot + parseInt(currentRow.cells[currentRow.cells.length - 1].innerHTML);
}
alert(tot.toString());
document.getElementById('total').innerHTML = tot.toString();
}
function addnewrow() {
var n = ($('.details tr').length - 0) + 1;
var tr = '<tr>' +
'<td class="no">' + n + '</td>' +
'<td><input type="text" name="items" id="items" class="form-control items" data-provide="typeahead" autocomplete="off" /></td>' +
'<td><textarea name="size" id="size" class="form-control size" autocomplete="off"></textarea></td>' +
'<td><input type="text" name="qty" id="qty" class="form-control qty" autocomplete="off"/></td>' +
'<td><input type="text" name="unit" id="unit" class="form-control unit" autocomplete="off"/></td>' +
'<td><input type="text" name="price" id="price" class="form-control price" autocomplete="off"/></td>' +
'<td><input type="text" name="tax" id="tax" class="form-control tax" data-provide="typeahead" autocomplete="off" /></td>' +
'<td><input type="text" name="dis" id="dis" class="form-control dis" autocomplete="off" /></td>' +
'<td><input type="text" name="amt" id="amt" class="form-control amt" autocomplete="off" /></td>' +
'<td><button class="btn btn-danger remove">X</button></td>' +
'</tr>';
$('.details').append(tr);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table table-bordered" id="stock">
<thead>
<tr>
<td>Sr no.</td>
<td>Product Name</td>
<td>Qty</td>
<td>Rate</td>
<td>Total</td>
<td><input type="button" name="add" id="add" value="+" class="btn btn-warning" /></td>
</tr>
</thead>
<tbody class="details">
<tr>
<td class="no">1</td>
<td><input type="text" name="items" id="items" class="form-control items" data-provide="typeahead" autocomplete="off" /></td>
<td><input type="text" name="qty" id="qty" class="form-control qty" autocomplete="off" /></td>
<td><input type="text" name="price" id="price" class="form-control price" autocomplete="off" /></td>
<td><input type="text" name="amt" id="amt" class="form-control amt" autocomplete="off" /></td>
<td><button class="btn btn-danger remove">X</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="3" style="text-align:right;">Total</th>
<th colspan="2" id="total" class="total"><b>$</b></th>
</tr>
</tfoot>
</table>

Categories

Resources