Jump to content

Auto calculation not happening for dynamic rows


Go to solution Solved by denno020,

Recommended Posts

Hi,

I am adding rows dynamically with autofilled values from database. After adding it, it has to calculate total. Now it is calculating total only for 1st row. for 2nd row onwards it is not calculating anything. And also overall total is not happening.

Here is my code

html form

<table class="table table-bordered">  
                        <tr>
                        <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>  
                            <th>No</th>  
                            <th>Item ID</th>  
                            <th>Description</th>
                            <th>UOM</th>    
                             <th>Price</th>
                            <th>Tax</th>    
                            <th>Quantity</th>  
                            <th>Discount</th>  
                            <th>Amount</th>  
                           
                        </tr>  
                        
                            <tr> 
                                <td><input type='checkbox' class='case'/></td> 
                               <td><span id='snum'>1.</span></td>
                                <td><input type="text" class="form-control" id="productcode_1" name="productcode[]"></td> 
                                <td><input type="text" class="form-control" id="description_1" name="description[]"></td> 
                                <td><input type="text" class="form-control" id="uom_1" name="uom[]"></td> 
                                <td><input type="text" class="form-control price" id="price_1" name="price[]"></td>
                                <td><input type="text" class="form-control tax" id="tax_1" name="tax[]"></td>    
                                <td><input type="text" class="form-control quantity" id="quantity_1" name="quantity[]"></td>  
                                <td><input type="text" class="form-control discount" id="discount_1" name="discount[]"></td>  
                                <td><input type="text" class="form-control amount" id="amount_1" name="amount[]"></td>  
                               <td><button type="button" class='btn btn-danger delete'>-</button></td>
						<td><button type="button" class='btn btn-success addmore'>+ </button></td>
</tr>  

<tfoot>  
<th></th>  
<th></th>  
<th></th>  
<th></th>  
<th></th>  
<th style="text-align:center;" class="total">0<b></b></th>  
</tfoot>  
  
</table>

Javascript

$(".delete").on('click', function() {
	$('.case:checkbox:checked').parents("tr").remove();
	$('.check_all').prop("checked", false); 
	check();
});
var i=$('table tr').length-1;


$(".addmore").on('click',function(){
	count=$('table tr').length-1;
	
    var data="<tr><td><input type='checkbox' class='case'/></td><td><span id='snum"+i+"'>"+count+".</span></td>";
    data +="<td><input class='form-control' type='text' id='productcode_"+i+"' name='productcode[]'/></td> <td><input class='form-control' type='text' id='description_"+i+"' name='description[]'/></td><td><input class='form-control' type='text' id='uom_"+i+"' name='uom[]'/></td><td><input class='form-control' type='text' id='price_"+i+"' name='price[]'/></td><td><input class='form-control' type='text' id='tax_"+i+"' name='tax[]'/></td><td><input class='form-control' type='text' id='quantity_"+i+"' name='quantity[]'/></td><td><input class='form-control' type='text' id='discount_"+i+"' name='discount[]'/></td><td><input class='form-control' type='text' id='amount_"+i+"' name='amount[]'/></td></tr>";
	$('table').append(data);
	row = i ;
	
	$('#productcode_'+i).autocomplete({
  	source: function( request, response ) {
  		$.ajax({
  			url : 'ajax.php',
  			dataType: "json",
  			method: 'post',
			data: {
			   name_startsWith: request.term,
			   type: 'items_table',
			   row_num : row
			   
			},
			
			 success: function( data ) {
				 response( $.map( data, function( item ) {
				 	var code = item.split("|");
					
					return {
						label: code[0],
						value: code[0],
						data : item
						
					}
				}));
			}
  		});
  	},
	
  	autoFocus: true,	      	
  	minLength: 0,
  	select: function( event, ui ) {
		var names = ui.item.data.split("|");
		id_arr = $(this).attr('id');
  		id = id_arr.split("_			
		$('#description_'+id[1]).val(names[1]);
		$('#uom_'+id[1]).val(names[2]);
		$('#price_'+id[1]).val(names[3]);
		$('#tax'+id[1]).val(names[4]);
	}		      	
  });
  
  
	i++;
	
	
});
				
function select_all() {
	$('input[class=case]:checkbox').each(function(){ 
		if($('input[class=check_all]:checkbox:checked').length == 0){ 
			$(this).prop("checked", false); 
		} else {
			$(this).prop("checked", true); 
		} 
	});
}
$('body').delegate('.quantity,.price,.discount,.tax','keyup',function()  
{  
var tr= $(this).parent().parent();  
var qty=tr.find('.quantity').valr price=tr.find('.price').val tax=tr.find('.tax').val 
var dis=tr.find('.discount').valr amt =(qty * price)-(qty * price *dis)/100;
var tax1 = (amt)* (tax/100);  
tr.find('.amount').val(tax1al();  
});  
function total()  
{  
var t=0;  
$('.amount').each(function(i,e)   
{  
var amt =$(this).val()-0;  
t+=tax1;  
});  
$('.total').html(t);  
}  

function check(){
	obj=$('table tr').find('span');
	$.each( obj, function( key, value ) {
		id=value.id;
		$('#'+id).html(key+1);
	});
}
										
$('#productcode_1').autocomplete({
	source: function( request, response ) {
		$.ajax({
			url : 'ajax.php',
			dataType: "json",
			method: 'post',
			data: {
			   name_startsWith: request.term,
			   type: 'items_table',
			   row_num : 1
			},
			 success: function( data ) {
				 response( $.map( data, function( item ) {
				 	var code = item.split("|");
					return {
						label: code[0],
						value: code[0],
						data : item
					}
				}));
			}
		});
	},
	autoFocus: true,	      	
	minLength: 0,
	select: function( event, ui ) {
		var names = ui.item.data.split("|");						
		$('#description_1').val(names[1]);
		$('#uom_1').val(names[2]);
		$('#price_1').val(names[3]);
		$('#tax_1').val(names[4]);
	}		      	
});

ajax.php

 <?php
require_once '../connect.php';
if($_POST['type'] == 'items_table'){
    $row_num = $_POST['row_num'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT items.iid, items.description, items.uom, items.selling_price, items.tax_id, taxes.tax_id, taxes.name, taxes.rate FROM items INNER JOIN taxes ON items.tax_id=taxes.tax_id where items.iid LIKE '".strtoupper($name)."%'";
    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['iid'].'|'.$row['description'].'|'.$row['uom'].'|'.$row['selling_price'].'|'.$row['rate'].'|'.$row_num;
        
        array_push($data, $name);    
    }    
    echo json_encode($data);
}
?> 

Only 1st row total is getting calculated.

Link to post
Share on other sites

Could you please create a jsFiddle or something, I tried copying your code into one myself but I was getting syntax errors, so it might be worth you getting it to work (well work but not work in jsFiddle), then we can have a good look at it.

Link to post
Share on other sites
  • Solution

Here you go: https://jsfiddle.net/cwmoo4hm/1/

 

Turns out the rows you were injecting into the HTML didn't have the classes that you attached your event listener to (.price, .tax, .quantity etc).

 

There's another issue with the new row that is added, as the new row seems to have an extra input, but at least your calculation is working as you requested

  • Like 1
Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.