Calculate gst for receipt - javascript

This is actually for a shop receipt but i need to regenerate it into a school receipt. ie, i need the tax1 value auto generate as 5% and tax2 auto genetrate as 6% and calculate it
and also no quantity needed.
<script>
$(document).ready(function(){
var final_total_amt = $('#final_total_amt').text();
var count = 1;
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<tr id="row_id_'+count+'">';
html_code += '<td><span id="sr_no">'+count+'</span></td>';
html_code += '<td><input type="text" name="item_name[]" id="item_name'+count+'" class="form-control input-sm" /></td>';
html_code += '<td><input type="text" name="order_item_quantity[]" id="order_item_quantity'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_quantity" /></td>';
html_code += '<td><input type="text" name="order_item_price[]" id="order_item_price'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_price" /></td>';
html_code += '<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';
html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';
html_code += '<td><input type="text" name="order_item_tax2_rate[]" id="order_item_tax2_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax2_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax2_amount[]" id="order_item_tax2_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax2_amount" /></td>';
html_code += '<td><input type="text" name="order_item_tax3_rate[]" id="order_item_tax3_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax3_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax3_amount[]" id="order_item_tax3_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax3_amount" /></td>';
html_code += '<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';
html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
html_code += '</tr>';
$('#invoice-item-table').append(html_code);
});
$(document).on('click', '.remove_row', function(){
var row_id = $(this).attr("id");
var total_item_amount = $('#order_item_final_amount'+row_id).val();
var final_amount = $('#final_total_amt').text();
var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
$('#final_total_amt').text(result_amount);
$('#row_id_'+row_id).remove();
count--;
$('#total_item').val(count);
});
function cal_final_total(count)
{
var final_item_total = 0;
for(j=1; j<=count; j++)
{
var quantity = 0;
var price = 0;
var actual_amount = 0;
var tax1_rate = 0;
var tax1_amount = 0;
var tax2_rate = 0;
var tax2_amount = 0;
var tax3_rate = 0;
var tax3_amount = 0;
var item_total = 0;
quantity = $('#order_item_quantity'+j).val();
if(quantity > 0)
{
price = $('#order_item_price'+j).val();
if(price > 0)
{
actual_amount = parseFloat(quantity) * parseFloat(price);
$('#order_item_actual_amount'+j).val(actual_amount);
tax1_rate = $('#order_item_tax1_rate'+j).val();
if(tax1_rate > 0)
{
tax1_amount = parseFloat(actual_amount)*parseFloat(tax1_rate)/100;
$('#order_item_tax1_amount'+j).val(tax1_amount);
}
tax2_rate = $('#order_item_tax2_rate'+j).val();
if(tax2_rate > 0)
{
tax2_amount = parseFloat(actual_amount)*parseFloat(tax2_rate)/100;
$('#order_item_tax2_amount'+j).val(tax2_amount);
}
tax3_rate = $('#order_item_tax3_rate'+j).val();
if(tax3_rate > 0)
{
tax3_amount = parseFloat(actual_amount)*parseFloat(tax3_rate)/100;
$('#order_item_tax3_amount'+j).val(tax3_amount);
}
item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
$('#order_item_final_amount'+j).val(item_total);
}
}
}
$('#final_total_amt').text(final_item_total);
}
$(document).on('blur', '.order_item_price', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax1_rate', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax2_rate', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax3_rate', function(){
cal_final_total(count);
});
$('#create_invoice').click(function(){
if($.trim($('#order_receiver_name').val()).length == 0)
{
alert("Please Enter Reciever Name");
return false;
}
if($.trim($('#order_no').val()).length == 0)
{
alert("Please Enter Invoice Number");
return false;
}
if($.trim($('#order_date').val()).length == 0)
{
alert("Please Select Invoice Date");
return false;
}
for(var no=1; no<=count; no++)
{
if($.trim($('#item_name'+no).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+no).focus();
return false;
}
if($.trim($('#order_item_quantity'+no).val()).length == 0)
{
alert("Please Enter Quantity");
$('#order_item_quantity'+no).focus();
return false;
}
if($.trim($('#order_item_price'+no).val()).length == 0)
{
alert("Please Enter Price");
$('#order_item_price'+no).focus();
return false;
}
}
$('#invoice_form').submit();
});
});
</script>
I dont know how to recode this to a school receipt. please any can recode this with this same values like no quanitity required , tax1 should be having default value as 5% and tax2 with value 6% and calculate it

Related

ajax is not working inside for loop

i am creating an dynamic invoice stystem... if i select itemcode then it displays item brand of that item code in my brand input id..if i add new item
then i click on plus button to add new item then i again select a new item code2 then it displays item brand2 of that item code2...so this loop is going on agiain and agian.
my ajax call is not working or some error in ajax code....i cant find the error..if i dint use ajax call only display data of selected var itemp then it displays selected data itemp in brand but using ajax call and find brand of selected data itemp it didn't works.. please anyone can help me.
here is my javascript ajax call...
function getprods(val) {
for (j = 1; j <= count; j++) {
var itemp = $('#item_code' + j).val();
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: 'state_id=' + itemp,
dataType: 'json',
success: function (data) {
var len = data.length;
if (len > 0) {
var id = data[0]['id'];
var brand = data[0]['brand'];
document.getElementById('brand' + j).value = brand;
}
}
});
}
}
And here is my ajax_getitems.php file
<?php
include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";
$result = mysqli_query($conn, $sql);
$users_arr = array();
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$brand = $row['brand'];
$users_arr[] = array("id" => $id,
"brand" => $brand
);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
?>
here is my full html code
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<link rel="stylesheet" href="css2/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="quotation/jquery-ui.min.css">
<script src="js2/jquery.min.js"></script>
<script src="js2/bootstrap.min.js"></script>
<script src="quotation/js/jquery-ui.js"></script>
<script src="js2/jquery.dataTables.min.js"></script>
<script src="js2/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="css2/dataTables.bootstrap.min.css">
<style>
/* Remove the navbar's default margin-bottom and rounded borders */
.navbar {
margin-bottom: 4px;
border-radius: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
.carousel-inner img {
width: 100%; /* Set width to 100% */
margin: auto;
min-height:200px;
}
.navbar-brand
{
padding:5px 40px;
}
.navbar-brand:hover
{
background-color:#ffffff;
}
/* Hide the carousel text when the screen is less than 600 pixels wide */
#media (max-width: 600px) {
.carousel-caption {
display: none;
}
}
</style>
</head>
<body>
<style>
.box
{
width: 100%;
max-width: 1390px;
border-radius: 5px;
border:1px solid #ccc;
padding: 15px;
margin: 0 auto;
margin-top:50px;
box-sizing:border-box;
}
</style>
<link rel="stylesheet" href="css2/datepicker.css">
<script src="js2/bootstrap-datepicker1.js"></script>
<script>
$(document).ready(function(){
$('#order_date').datepicker({
format: "yyyy-mm-dd",
autoclose: true
});
});
</script>
<script>
$(document).ready(function(){
$(document).on('keydown', '.name', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var id = response[0]['id'];
var phone = response[0]['phone'];
var email = response[0]['email'];
var address = response[0]['address'];
var gst = response[0]['gst'];
document.getElementById('phone').value = phone;
document.getElementById('email').value = email;
document.getElementById('address').value = address;
document.getElementById('gst').value = gst;
}
}
});
return false;
}
});
});
});
function getproduct(val) {
$.ajax({
url: 'ajax_getproduct.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var item = data[0]['item'];
var subcat = data[0]['subcat'];
var brand = data[0]['brand'];
var model = data[0]['model'];
var specification = data[0]['specification'];
var unitrate = data[0]['unitrate'];
var unitmesure = data[0]['unitmesure'];
document.getElementById('item').value = item;
document.getElementById('subcat').value = subcat;
document.getElementById('brand').value = brand;
document.getElementById('model').value = model;
document.getElementById('Specification').value = specification;
document.getElementById('unitrate1').value = unitrate;
document.getElementById('unitmesure').value = unitmesure;
}
}
});
}
</script>
<div class="container-fluid">
<form method="post" id="invoice_form">
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<td colspan="2" align="center"><h2 style="margin-top:10.5px">Create Quotation</h2></td>
</tr>
<tr>
<td colspan="2">
<div class="row">
<div class="col-md-8">
To,<br />
<b>RECEIVER (BILL TO)</b><br />
<input type="text" name="name" id="name" class="form-control name" placeholder="Enter Receiver Name" />
<textarea name="address" id="address" class="form-control" placeholder="Enter Billing Address"></textarea>
</div>
<div class="col-md-4">
<br />
<input type="text" name="phone" id="phone" class="form-control input-sm" placeholder="Phone No." />
<input type="text" name="email" id="email" class="form-control input-sm" placeholder="Email" />
<input type="text" name="gst" id="gst" class="form-control input-sm" placeholder="GST" />
</div>
</div>
<br />
<table id="invoice-item-table" class="table table-bordered">
<tr>
<th>Sr No.</th>
<th>Item Code</th>
<th>Brand</th>
<th>Model</th>
<th>Specification</th>
<th>Unit Rate</th>
<th>Quantity</th>
<th>Actual Amt.</th>
<th colspan="2">Discount (%)</th>
<th rowspan="2">Total</th>
<th rowspan="2"></th>
</tr>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Rate</th>
<th></th>
<th>Amt.</th>
</tr>
<tr>
<td><span id="sr_no">1</span></td>
<td><select type="text" name="item_code[]" id="item_code" class="form-control input-sm" onChange="getproduct(this.value);" >
<option value=""></option>
<?php
include "conn.php";
$sql = "SELECT * FROM `product`";
$run = mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run))
{
?>
<option><?php echo $row['code']; ?></option>
<?php } ?>
</select>
<input type="hidden" name="item[]" id="item">
<input type="hidden" name="subcat[]" id="subcat">
</td>
<td>
<input type="text" name="brand[]" id="brand" class="form-control input-sm" readonly>
</td>
<td>
<input type="text" name="model[]" id="model" class="form-control input-sm" readonly>
</td>
<td>
<textarea name="Specification[]" id="Specification" class="form-control" readonly></textarea>
</td>
<td><input type="text" name="unitrate[]" id="unitrate1" data-srno="1" class="form-control input-sm unitrate" />
<input type="hidden" name="unitmesure" id="unitmesure">
</td>
<td><input type="text" name="qty[]" id="qty1" data-srno="1" class="form-control input-sm number_only qty" /></td>
<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount1" data-srno="1" class="form-control input-sm order_item_actual_amount" readonly /></td>
<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate1" data-srno="1" class="form-control input-sm number_only order_item_tax1_rate" /></td>
<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount1" data-srno="1" readonly class="form-control input-sm order_item_tax1_amount" /></td>
<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount1" data-srno="1" readonly class="form-control input-sm order_item_final_amount" /></td>
<td></td>
</tr>
</table>
<div align="right">
<button type="button" name="add_row" id="add_row" class="btn btn-success btn-xs">+</button>
</div>
</td>
</tr>
<tr>
<td align="right"><b>Total</td>
<td align="right"><b><span id="final_total_amt"></span></b></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="total_item" id="total_item" value="1" />
<input type="submit" name="create_invoice" id="create_invoice" class="btn btn-info" value="Create" />
</td>
</tr>
<tr>
</tr>
</table>
</div>
</form>
<script>
$(document).ready(function(){
var final_total_amt = $('#final_total_amt').text();
var count = 1;
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<tr id="row_id_'+count+'">';
html_code += '<td><span id="sr_no">'+count+'</span></td>';
html_code += '<td><select name="item_code[]" id="item_code'+count+'" class="form-control input-sm item_code"><option></option><?php $sql='Select * from product'; $run=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($run)){ echo '<option>'.$row['code'].'</option>'; } ?></select><input type="hidden" name="item[]" id="item'+count+'"><input type="hidden" name="subcat[]" id="subcat'+count+'"></td>';
html_code += '<td><input type="text" name="brand[]" id="brand'+count+'" class="form-control input-sm" readonly></td>';
html_code += '<td><input type="text" name="model[]" id="model'+count+'" class="form-control input-sm" readonly></td>';
html_code += '<td><textarea name="Specification[]" id="Specification'+count+'" class="form-control" readonly></textarea></td>';
html_code += '<td><input type="text" name="unitrate[]" id="unitrate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only unitrate" /><input type="hidden" name="unitmesure[]" id="unitmesure'+count+'"></td>';
html_code += '<td><input type="text" name="qty[]" id="qty'+count+'" data-srno="'+count+'" class="form-control input-sm number_only qty" /></td>';
html_code += '<td><input type="text" name="order_item_actual_amount[]" id="order_item_actual_amount'+count+'" data-srno="'+count+'" class="form-control input-sm order_item_actual_amount" readonly /></td>';
html_code += '<td><input type="text" name="order_item_tax1_rate[]" id="order_item_tax1_rate'+count+'" data-srno="'+count+'" class="form-control input-sm number_only order_item_tax1_rate" /></td>';
html_code += '<td><input type="text" name="order_item_tax1_amount[]" id="order_item_tax1_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_tax1_amount" /></td>';
html_code += '<td><input type="text" name="order_item_final_amount[]" id="order_item_final_amount'+count+'" data-srno="'+count+'" readonly class="form-control input-sm order_item_final_amount" /></td>';
html_code += '<td><button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button></td>';
html_code += '</tr>';
$('#invoice-item-table').append(html_code);
});
$(document).on('click', '.remove_row', function(){
var row_id = $(this).attr("id");
var total_item_amount = $('#order_item_final_amount'+row_id).val();
var final_amount = $('#final_total_amt').text();
var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
$('#final_total_amt').text(result_amount);
$('#row_id_'+row_id).remove();
count--;
$('#total_item').val(count);
});
function cal_final_total(count)
{
var final_item_total = 0;
for(j=1; j<=count; j++)
{
var quantity = 0;
var price = 0;
var actual_amount = 0;
var tax1_rate = 0;
var tax1_amount = 0;
var tax2_rate = 0;
var tax2_amount = 0;
var tax3_rate = 0;
var tax3_amount = 0;
var item_total = 0;
quantity = $('#unitrate'+j).val();
if(quantity > 0)
{
price = $('#qty'+j).val();
if(price > 0)
{
actual_amount = parseFloat(quantity) * parseFloat(price);
$('#order_item_actual_amount'+j).val(actual_amount);
tax1_rate = $('#order_item_tax1_rate'+j).val();
if(tax1_rate > 0)
{
tax1_amount = -(parseFloat(actual_amount)*parseFloat(tax1_rate)/100);
$('#order_item_tax1_amount'+j).val(tax1_amount);
}
item_total = parseFloat(actual_amount) + parseFloat(tax1_amount) + parseFloat(tax2_amount) + parseFloat(tax3_amount);
final_item_total = parseFloat(final_item_total) + parseFloat(item_total);
$('#order_item_final_amount'+j).val(item_total);
}
}
}
$('#final_total_amt').text(final_item_total);
}
function getprods()
{
for(j=1; j<=count; j++)
{
var itemp = $('#item_code'+j).val();
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: 'state_id='+itemp,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var brand = data[0]['brand'];
document.getElementById('brand'+j).value = brand;
}
}
});
}
}
$(document).on('blur', '.qty', function(){
cal_final_total(count);
});
$(document).on('blur', '.order_item_tax1_rate', function(){
cal_final_total(count);
});
$(document).on('change', '.item_code', function(){
getprods(this.value);
});
$('#create_invoice').click(function(){
if($.trim($('#order_receiver_name').val()).length == 0)
{
alert("Please Enter Reciever Name");
return false;
}
if($.trim($('#order_no').val()).length == 0)
{
alert("Please Enter Invoice Number");
return false;
}
if($.trim($('#order_date').val()).length == 0)
{
alert("Please Select Invoice Date");
return false;
}
for(var no=1; no<=count; no++)
{
if($.trim($('#item_name'+no).val()).length == 0)
{
alert("Please Enter Item Name");
$('#item_name'+no).focus();
return false;
}
if($.trim($('#unitrate'+no).val()).length == 0)
{
alert("Please Enter Quantity");
$('#unitrate'+no).focus();
return false;
}
if($.trim($('#qty'+no).val()).length == 0)
{
alert("Please Enter Price");
$('#qty'+no).focus();
return false;
}
}
$('#invoice_form').submit();
});
});
</script>
<script>
$(document).ready(function(){
$('.number_only').keypress(function(e){
return isNumbers(e, this);
});
function isNumbers(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
</script>
</body>
</html>
<?php
include('conn2.php');
if(isset($_POST['create_invoice']))
{
$order_receiver_name=$_POST['order_receiver_name'];
$order_receiver_address=$_POST['order_receiver_address'];
$order_no=$_POST['order_no'];
$order_date=$_POST['order_date'];
$order_total_before_tax = 0;
$order_total_tax1 = 0;
$order_total_tax2 = 0;
$order_total_tax3 = 0;
$order_total_tax = 0;
$order_total_after_tax = 0;
date_default_timezone_set('Asia/Kolkata');
$current = date('d-m-Y H:i:s');
$sql = "INSERT INTO `tbl_order`(`order_no`, `order_date`, `order_receiver_name`, `order_receiver_address`, `order_total_before_tax`, `order_total_tax1`, `order_total_tax2`, `order_total_tax3`, `order_total_tax`, `order_total_after_tax`, `order_datetime`) VALUES ('$order_no','$order_date','$order_receiver_name','$order_receiver_address','$order_total_before_tax','$order_total_tax1','$order_total_tax2','$order_total_tax3','$order_total_tax','$order_total_after_tax','$current')";
$run = mysqli_query($conn, $sql);
if($run)
{
echo "<script>alert('Inserted Successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
$last_id = mysqli_insert_id($conn);
for($count=0; $count<$_POST["total_item"]; $count++)
{
$item_name = $_POST['item_name'][$count];
$unitrate = $_POST['unitrate'][$count];
$qty = $_POST['qty'][$count];
$order_item_actual_amount = $_POST['order_item_actual_amount'][$count];
$order_item_tax1_rate = $_POST['order_item_tax1_rate'][$count];
$order_item_tax1_amount = $_POST['order_item_tax1_amount'][$count];
$order_item_tax2_rate = $_POST['order_item_tax2_rate'][$count];
$order_item_tax2_amount = $_POST['order_item_tax2_amount'][$count];
$order_item_tax3_rate = $_POST['order_item_tax3_rate'][$count];
$order_item_tax3_amount = $_POST['order_item_tax3_amount'][$count];
$order_item_final_amount = $_POST['order_item_final_amount'][$count];
$sql2 = "INSERT INTO `tbl_order_item`(`order_id`, `item_name`, `order_item_quantity`, `order_item_price`, `order_item_actual_amount`, `order_item_tax1_rate`, `order_item_tax1_amount`, `order_item_tax2_rate`, `order_item_tax2_amount`, `order_item_tax3_rate`, `order_item_tax3_amount`, `order_item_final_amount`) VALUES ('$last_id','$item_name','$order_item_quantity','$order_item_price','$order_item_actual_amount','$order_item_tax1_rate','$order_item_tax1_amount','$order_item_tax2_rate','$order_item_tax2_amount','$order_item_tax3_rate','$order_item_tax3_amount','$order_item_final_amount')";
$run2 = mysqli_query($conn, $sql2);
if($run2)
{
echo "<script>alert('inserted successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
$order_total_before_tax = $order_total_before_tax + floatval(trim($_POST["order_item_actual_amount"][$count]));
$order_total_tax1 = $order_total_tax1 + floatval(trim($_POST["order_item_tax1_amount"][$count]));
$order_total_tax2 = $order_total_tax2 + floatval(trim($_POST["order_item_tax2_amount"][$count]));
$order_total_tax3 = $order_total_tax3 + floatval(trim($_POST["order_item_tax3_amount"][$count]));
$order_total_after_tax = $order_total_after_tax + floatval(trim($_POST["order_item_final_amount"][$count]));
}
$order_total_tax = $order_total_tax1 + $order_total_tax2 + $order_total_tax3;
$sql3 = "UPDATE `tbl_order` SET `order_total_before_tax`='$order_total_before_tax',`order_total_tax1`='$order_total_tax1',`order_total_tax2`='$order_total_tax2',`order_total_tax3`='$order_total_tax3',`order_total_tax`='$order_total_tax',`order_total_after_tax`='$order_total_after_tax' WHERE `order_id`='$last_id'";
$run3 = mysqli_query($conn, $sql3);
if($run3)
{
echo "<script>alert('inserted successfully')</script>";
}
else{
echo("Error description: " . mysqli_error($conn));
}
}
?>
Edit your php file as below.
<?php
include('conn.php');
$model = $_POST['state_id'];
$sql = "SELECT * FROM product WHERE code='$model'";
$result = mysqli_query($conn, $sql);
// encoding array to json format
echo json_encode($result);
exit;
?>
Then edit your ajax part like below,
function getprods(itemp) {
$.ajax({
url: 'ajax_getitems.php',
type: 'POST',
data: { 'state_id':itemp },
cache: false,
success: function (data) {
var json = $.parseJSON(data);
$.each(json, function (index, item) {
var id = item.id;
var brand = item.brand;
document.getElementById('brand' + index).value = brand;
}
}
});
}
adding property async: false inside ajax may solve this issue.
$.ajax({
url:"get_response_filter.php",
method: "POST",
dataType: 'json',
async: false,
j <= count;
But where is 'count' var?

dynamically generate a list dropdown in javascript from JSON data

I have generated a form and storing it into a JS variable but the problem is I want to generate a dropdown list. Data for that dropdown is present in an array into JSON. I tried to concat values using a for loop but that didn't work
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">'
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
+'<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>'
}
'</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}
See Commented for loop I've tried that as well but that is also not working.
This is how my json looks like
Please do code like below:
function(resp){
resp = JSON.parse(resp);
console.log(resp);
let dispData = '<form>'+
'<div class="form-group">'+
'<label>Item</label>'+
'<input type="text" class="form-control reas-item" id="'+resp["item_details"].master_id+'" value="'+resp["item_details"].item_name+'" disabled>'+
'</div>'+
'<div class="form-group">'+
'<label>Date</label>'+
'<input type="date" class="form-control reas-date">'+
'</div>'+
'<div class="form-group">'+
'<label>Quantity</label>'+
'<input type="number" class="form-control reas-quantity" min="1" max="'+resp["item_details"].quantity+'" value="'+resp["item_details"].quantity+'" >'+
'</div>'+
'<div class="form-group">'+
'<label>Reassign To:</label>'+
'<select class="form-control reas-staff">';
for (var i = 0; i < resp['trachers_list'].length; i++) {
var staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name;
dispData += '<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>';
}
dispData += '</select>'+
'</div>'+
'</form>';
/*for (var i = 0; i < resp['trachers_list'].length; i++) {
let staffName = resp['trachers_list'][i].first_name+" "+resp['trachers_list'][i].middle_name+" "+resp['trachers_list'][i].last_name
$(".reas-staff").html('<option value="'+resp['trachers_list'][i].wp_usr_id+'">'+staffName+'</option>');
}*/
}

Input values not adding on keyUp jquery

I have a running code snippet that dynamically adds input boxes to a form that is working so fine, however, am trying to get totals of the values from the input boxes but nothing seem to be working. The total area is only showing 0 but not giving me correct results.
Here is my code:
JAVASCRIPT TO DISPLAY THE TABLE WITH FORM
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input class="qty" type="text" value="0" data-cubics="500"/></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td width="33%"><span class="cubics"></span>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
JAVASCRIPT TO DO THE MATH
<script>
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$('input.qty').keyup(function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on({
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
</script>
HTML CODE TO DISPLAY TOTALS
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span>
</td>
<td width="33%"><span class="totalcubics"></span>
</td>
</tr>
Any assistance to my problem is highly appreciated
I think your problem in
$(this).closest('td').next().find('span.cubics').text(val);
this mean go to the next td and find the span and there is no span in the next td .. you can use
$(this).closest('tr').find('span.cubics').text(val);
or
$(this).closest('td').next().next().find('span.cubics').text(val);
and while you append the row dynamically you need to use
$(document).on('keyup' , 'input.qty' , function () {
instead of
$('input.qty').keyup(function () {
You need to recreate $summands each time you add a row to the table. Insert the line to do so after adding the row.
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input class="qty" type="text" value="0" data-cubics="500"/></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td width="33%"><span class="cubics"></span>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
$summands = $form.find('input.qty'); //*************** add this line
});
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$('input.qty').keyup(function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on(
{
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
}); // end of document ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="insert_form" onsubmit="return false">
<table>
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span></td>
<td width="33%"><span class="totalcubics"></span></td>
</tr>
</table>
<button type="button" class="add">add</button>
<table id="item_table">
</table>
</form>
At the moment you are creating summands collection with no elements, before any rows have been added.
With the help of #tracktor53, i managed to get a fix for my problem, below is my updated code;
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><input class="qty" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
$summands = $form.find('input.qty'); //*************** added this line
});
And with #mohamed's help, this line $(this).closest('td').next().find('span.cubics').text(val); was looking for the next <td> which in actual sense, the next <td> was an input field but not the one with <span id='cubics'></span> so, i had to adjust that to this;
html += '<td><input class="qty" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
Then after i had to use
$(document).on('keyup' , 'input.qty' , function () {
instead of
$('input.qty').keyup(function () {
Now everything is working fine only that i want to multiply select option values with qty input from this line;
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>'
Any further assistance about this is highly welcome

How to make autocomplete for form dynamic

i have trouble using autocomplete with dynamic created input. I can't get autocomplete to bind to the new inputs.
This code autocomplete I used on the first input
$(function() {
$( '#nama-0').autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode-0').val(ui.item.kode);
$('#harga-0').val(ui.item.harga);
}
});
});
and this new table row with input:
$('#tambah').click(function() {
var i = $('input').size() + 1,
input = '<tr id="box' + i + '">';
input += '<td><input id="nama-' + i + '" name="nama_input[]" autocomplete="off" class="nama form-control" /></td>';
input += '<td><input id="kode-' + i + '" name="kode_input[]" readonly="readonly" class="form-control" /></td>';
input += '<td><input id="harga-' + i + '" name="harga_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="jumlah-' + i + '" name="jumlah_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="total-' + i + '" name="total_input[]" class="total form-control" readonly="readonly" /></td>';
input += '<td><button id="hapus" class="btn btn-default"><b>Hapus</b></button></td>'
input += '</tr>';
$('#box').append(input);
i++;
return false;
});
i think the problem I guess the problem is in the use of dynamic input id attribute. how to write id of dynamic input, and apply them in autocomplete? any help appreciated.
Your issue is because the #nama-N element doesn't exist in the DOM when you try to initialise the autocomplete function on it.
To fix this, move your first block of code inside the click handler, after append() has been called. Try this:
$('#tambah').click(function(e) {
e.preventDefault();
var i = $('input').size() + 1;
var input = '<tr id="box' + i + '">';
input += '<td><input id="nama-' + i + '" name="nama_input[]" autocomplete="off" class="nama form-control" /></td>';
input += '<td><input id="kode-' + i + '" name="kode_input[]" readonly="readonly" class="form-control" /></td>';
input += '<td><input id="harga-' + i + '" name="harga_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="jumlah-' + i + '" name="jumlah_input[]" type="number" autocomplete="off" class="hitung form-control" /></td>';
input += '<td><input id="total-' + i + '" name="total_input[]" class="total form-control" readonly="readonly" /></td>';
input += '<td><button id="hapus" class="btn btn-default"><b>Hapus</b></button></td>'
input += '</tr>';
$('#box').append(input);
// attach autocomplete here as the element now exists in the DOM
$('#nama-' + i).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$('#kode-0').val(ui.item.kode);
$('#harga-0').val(ui.item.harga);
}
});
});

Calculate total of all dynamic items upon submit of form including copied items

I am trying to calculate the total of a list of dynamic form option items, example :
product name
product description
quantity
price
total
I have a script that automatically adds item rows :
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type="text" data-type="productCode" name="data[Invoice][itemNo][]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="data[Invoice][itemName][]" id="itemName_'+i+'" class="form-control" autocomplete="off"></td>';
html += '<td><input type="text" name="data[Invoice][price][]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][quantity][]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][total][]" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input class="case" type="checkbox" name="data[Invoice][staged][]" id="itemStaged_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
and the script that does the totalling :
$(document).on('change keyup blur','#tax',function(){
calculateTotal();
});
//total price calculation
function calculateTotal(){
subTotal = 0 ; total = 0;
$('.totalLinePrice').each(function(){
if($(this).val() != '' )subTotal += parseFloat( $(this).val() );
});
$('#subTotal').val( subTotal.toFixed(2) );
tax = $('#tax').val();
if(tax != '' && typeof(tax) != "undefined" ){
taxAmount = subTotal * ( parseFloat(tax) /100 );
$('#taxAmount').val(taxAmount.toFixed(2));
total = subTotal + taxAmount;
}else{
$('#taxAmount').val(0);
total = subTotal;
}
$('#totalAftertax').val( total.toFixed(2) );
calculateAmountDue();
}
So what happens now, you tab or press enter to cycle through the fields, and after you update the qty and tab through, it updates the total for that item, as well as the overall total.
The PROBLEM is that if you COPY and PASTE form fields using the following script :
//copies the selected table rows to new ones
$(".copy").on('click', function() {
var origs=$('.case:checkbox:checked');
for(var a=0; a<origs.length; a++) {
addNewRow();
var arr = origs.closest('tr')[a].id.split('_');
var id = arr[arr.length-1];
var dat = getValues(id);
setValues(i-1, dat);
}
$('#check_all').add(origs).prop("checked", false);
// Tried adding calculateTotal(); in this line to no avail...
});
The copied rows are not updated on the overall total. This is driving me insane, does anyone have a solution or tutorial on how to do this?
Requests : (show addNewRow function)
var addNewRow = function(id){
html = '<tr id="tr_'+i+'">';
html += '<input type="hidden" id="stock_'+i+'"/>';
html += '<input type="hidden" id="stockMaintainer_'+i+'" name="data[InvoiceDetail]['+i+'][stockMaintainer]" />';
html += '<input type="hidden" id="previousQuantity_'+i+'"/>';
html += '<input type="hidden" id="invoiceDetailId_'+i+'"/>';
html += '<td><input class="case" id="caseNo_'+i+'" type="checkbox" onkeyup="return tabE(this,event);"/></td>';
html += '<td class="prod_c"><input type="text" data-type="productCode" name="data[InvoiceDetail]['+i+'][product_id]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off" onkeyup="return tabE(this,event);">';
html +='<span class="add_icon" id="add_icon_'+i+'"> <i class="fa fa-plus-circle"></i></span>';
html +='<span class="subtract_icon" id="subtract_icon_'+i+'"><i class="fa fa-minus-circle"></i></span>';
html +='</td>';
html += '<td><input type="text" data-type="productName" name="data[InvoiceDetail]['+i+'][productName]" id="itemName_'+i+'" class="form-control" autocomplete="off" onkeyup="return tabE(this,event);"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][price]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[InvoiceDetail]['+i+'][quantity]" id="quantity_'+i+'" class="form-control changesNo quanyityChange" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;">';
html += '</td>';
html += '<td><input type="text" id="total_'+i+'" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail]['+i+'][staged]" id="staged_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail]['+i+'][added]" id="added_1'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select name="data[InvoiceDetail]['+i+'][location]" id="location_1'+i+'" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
html += '</tr>';
if( typeof id !== "undefined"){
$('#tr_'+id).after(html);
}else{
$('table').append(html);
}
$('#caseNo_'+i).focus();
i++;
}
(getValues) Code :
var getValues=function(id){
var inputs=$('#tr_'+id).find('select,input,textarea').filter('[name]');
var values={};
for(var i=0; i<inputs.length;i++){
var cur=inputs[i];
values[cur.name.match(/\[\w+]$/)||cur.name] = $(cur).is(':checkbox, :radio') ? cur.checked : cur.value;
}
return values;
};
(setValues) :
var setValues=function(id,values){
var inputs=$('#tr_'+id);
for(var i in values){
var cur=inputs.find('[name$="'+i+'"]');
if(cur.is(':checkbox, :radio')) {
cur.prop('checked', values[i]);
} else {
cur.val(values[i]);
}
}
};
The addNewRow function is not setting a name attribute on the total textbox.
However, your getValues and setValues functions are using the [name] attribute selector to get and set values in the cloned rows. Because addNewRow did not set the name attribute, the total value fails to populate in the cloned row, and therefore the total does not change because calculateTotal interprets this value as 0.
Problem code is here:
html += '<td><input type="text" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
Here is the fixed line of code: (and also remember to call calculateTotal in your copy handler)
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][total]" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
See working (but slightly simplified) snippet below: (or see the fiddle)
$(document).on('change keyup blur', '#tax', function() {
calculateTotal();
});
IsNumeric = tabE = function() {
return true
}
var i = 0;
var addNewRow = function(id) {
var html = '<tr id="tr_' + i + '">';
html += '<input type="hidden" id="stock_' + i + '"/>';
html += '<input type="hidden" id="stockMaintainer_' + i + '" name="data[InvoiceDetail][' + i + '][stockMaintainer]" />';
html += '<input type="hidden" id="previousQuantity_' + i + '"/>';
html += '<input type="hidden" id="invoiceDetailId_' + i + '"/>';
html += '<td><input class="case" id="caseNo_' + i + '" type="checkbox" onkeyup="return tabE(this,event);"/></td>';
html += '<td class="prod_c"><input type="text" data-type="productCode" name="data[InvoiceDetail][' + i + '][product_id]" id="itemNo_' + i + '" class="form-control autocomplete_txt" autocomplete="off" onkeyup="return tabE(this,event);">';
html += '<span class="add_icon" id="add_icon_' + i + '"> <i class="fa fa-plus-circle"></i></span>';
html += '<span class="subtract_icon" id="subtract_icon_' + i + '"><i class="fa fa-minus-circle"></i></span>';
html += '</td>';
html += '<td><input type="text" data-type="productName" name="data[InvoiceDetail][' + i + '][productName]" id="itemName_' + i + '" class="form-control" autocomplete="off" onkeyup="return tabE(this,event);"></td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][price]" id="price_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][quantity]" id="quantity_' + i + '" class="form-control changesNo quanyityChange" autocomplete="off" onkeypress="return IsNumeric(event);" onkeyup="return tabE(this,event);" ondrop="return false;" onpaste="return false;">';
html += '</td>';
html += '<td><input type="text" name="data[InvoiceDetail][' + i + '][total]" id="total_' + i + '" class="form-control totalLinePrice addNewRow" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail][' + i + '][staged]" id="staged_1' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="checkbox" name="data[InvoiceDetail][' + i + '][added]" id="added_1' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><select name="data[InvoiceDetail][' + i + '][location]" id="location_1' + i + '" class="form-control autocomplete_txt" autocomplete="off">';
html += '<option value="Used">Used</option>';
html += '<option value="RTS">RTS</option>';
html += '<option value="LAJ">LAJ</option>';
html += '</select></td>';
html += '</tr>';
if (typeof id !== "undefined") {
$('#tr_' + id).after(html);
} else {
$('table').append(html);
}
$('#caseNo_' + i).focus();
i++;
}
$(".addmore").on('click', function() {
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type="text" data-type="productCode" name="data[Invoice][itemNo][]" id="itemNo_' + i + '" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="productName" name="data[Invoice][itemName][]" id="itemName_' + i + '" class="form-control" autocomplete="off"></td>';
html += '<td><input type="text" name="data[Invoice][price][]" id="price_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][quantity][]" id="quantity_' + i + '" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input type="text" name="data[Invoice][total][]" id="total_' + i + '" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;"></td>';
html += '<td><input class="case" type="checkbox" name="data[Invoice][staged][]" id="itemStaged_' + i + '"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
//copies the selected table rows to new ones
$(".copy").on('click', function() {
var origs = $('.case:checkbox:checked');
for (var a = 0; a < origs.length; a++) {
addNewRow();
var arr = origs.closest('tr')[a].id.split('_');
var id = arr[arr.length - 1];
var dat = getValues(id);
setValues(i - 1, dat);
}
$('#check_all').add(origs).prop("checked", false);
calculateTotal();
});
//total price calculation
function calculateTotal() {
subTotal = 0;
total = 0;
$('.totalLinePrice').each(function() {
if ($(this).val() != '') subTotal += parseFloat($(this).val());
});
$('#subTotal').val(subTotal.toFixed(2));
tax = $('#tax').val();
if (tax != '' && typeof(tax) != "undefined") {
taxAmount = subTotal * (parseFloat(tax) / 100);
$('#taxAmount').val(taxAmount.toFixed(2));
total = subTotal + taxAmount;
} else {
$('#taxAmount').val(0);
total = subTotal;
}
$('#totalAftertax').val(total.toFixed(2));
//calculateAmountDue();
}
var getValues = function(id) {
var inputs = $('#tr_' + id).find('select,input,textarea').filter('[name]');
var values = {};
for (var i = 0; i < inputs.length; i++) {
var cur = inputs[i];
values[cur.name.match(/\[\w+]$/) || cur.name] = $(cur).is(':checkbox, :radio') ? cur.checked : cur.value;
}
return values;
};
var setValues = function(id, values) {
var inputs = $('#tr_' + id);
for (var i in values) {
var cur = inputs.find('[name$="' + i + '"]');
if (cur.is(':checkbox, :radio')) {
cur.prop('checked', values[i]);
} else {
cur.val(values[i]);
}
}
};
addNewRow()
addNewRow()
input {
width: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Tax rate
<input type="text" id="tax" value="8.7">
</div>
<div>
Tax amt
<input type="text" id="taxAmount" value="0">
</div>
<div>
Total
<input type="text" id="totalAftertax" value="0">
</div>
COPY CHECKED ROWS (check some rows first)
<table>
<thead>
<tr>
<th>copy</th>
<th>product code</th>
<th>product name</th>
<th>price</th>
<th>qty</th>
<th>total</th>
<th>staged</th>
<th>added</th>
<th>location</th>
</tr>
</thead>
</table>
Here you are calling calculateTotal(); function on change keyup and blur
events.this works as long as you interact with form elements.
but when you copy the row.you wont be interacting with textboxes.so those change,blur and keyup events wont get fired and as a result calculateTotal()
will not be executed.as a result you cant see any update on total value.
to overcome this you have to call calculateTotal() in copy function.

Categories