0

I want to calculate subtotal and total for my form

i tried some javascripts but dident worked for me

some of them were only for static table since i am adding dynamic rows they were not helpfull

can any one help me to add script

formula 1) subtotal = amount1+ amount2+...+ amount(n) 2) total = total - discount

here are my codes

 function calculateSubTotal()
{
     
    var SubTotal =  +amnt.value +  +amnt.value;
 
    document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
    }
        
    
document.getElementById("amnt").onchange = calculateSubTotal;
document.getElementById("amnt").onkeyup = calculateSubTotal;

function calculate(elm) {
    var tr = elm;
    while ((tr = tr.parentElement) && tr.tagName !== 'TR');
    var inputs = tr.querySelectorAll('input,select');

    var myBox1 = inputs[2].value;	
    var myBox2 = inputs[3].value;
    var myResult = myBox1 * myBox2;
    inputs[4].value = myResult;
}
		
var count = "1";
function addRow(in_tbl_name)
{
    var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
    // create row
    var row = document.createElement("TR");
    // create table cell 1
    var td1 = document.createElement("TD")
    var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"i_name[]\" PLACEHOLDER=\"Name\" SIZE=\"30\">";
  
   
    td1.innerHTML = strHtml1.replace(/!count!/g,count);
    // create table cell 2
    var td2 = document.createElement("TD")
    var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"i_desc[]\" PLACEHOLDER=\"Description\" SIZE=\"30\">";
    td2.innerHTML = strHtml2.replace(/!count!/g,count);
    // create table cell 3
    var td3 = document.createElement("TD")
    var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"i_qty[]\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
    td3.innerHTML = strHtml3.replace(/!count!/g,count);
    // create table cell 4
    var td4 = document.createElement("TD")
    var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"i_rate[]\" PLACEHOLDER=\"Rate\" ID=\"rate\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
    td4.innerHTML = strHtml4.replace(/!count!/g,count);
    // create table cell 5
    var td5 = document.createElement("TD")
    var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"i_amnt[]\" PLACEHOLDER=\"Amount\" ID=\"amnt\" >";
	
    td5.innerHTML = strHtml5.replace(/!count!/g,count);
	 // create table cell 4
    var td6 = document.createElement("TD")
    var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";
	
    td6.innerHTML = strHtml6.replace(/!count!/g,count);
	
    // append data to row
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    row.appendChild(td4);
    row.appendChild(td5);
	row.appendChild(td6);
    // add to count variable
    count = parseInt(count) + 1;
    // append row to table
    tbody.appendChild(row);
  }
  function delRow()
  {
    var current = window.event.srcElement;
    //here we will delete the line
    while ( (current = current.parentElement)  && current.tagName !="TR");
         current.parentElement.removeChild(current);
  }
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >
         	<h3> Add New Purchase</h3>
			<div class="vali-form">
           
           	<div class="col-md-3 form-group2 group-mail">
            <select required name="s_account">
			
            	<option >--Select Account Name--</option>
				<?php while ($row = mysqli_fetch_array($run)) {
   echo '<option value="'.$row['acc_name'].'">'.$row['acc_name'].'</option>';}?>

	
            </select>
            </div>
                       <div class="clearfix"> </div>
           
           <div class="col-md-4 form-group1 form-last">
              <label class="control-label">Reminder</label>
              <input type="text" name="s_rem" placeholder="" required="">
            </div>
           
           <div class="col-md-4 form-group1 group-mail">
              <label class="control-label">Invoice Date</label>
              <input type="date" name="s_idate" class="form-control1 ng-invalid ng-invalid-required" ng-model="model.date" placeholder="" required="">
            </div>
            <div class="col-md-4 form-group1 group-mail">
              <label class="control-label ">Due Date</label>
              <input type="date" name="s_ddate" class="form-control1 ng-invalid ng-invalid-required" ng-model="model.date" required="">
            </div></div>
            
         <div class="clearfix"> </div>

           
<div class="col-md-12 form-group1 form-last">
	<div class="table-responsive">
       <TABLE ID="tblPets" class="table table-striped table-bordered table-hover">
<tr>  
  
            <th><center>Item Name</center></th> 
			<th><center>Description</center></th> 
            
            <th><center>Qty.</center></th> 
           
            <th><center>Rate</center></th> 
            <th><center>Amount</center></th> 
            <th><center><INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row"></center></th>  

			
			
        </tr>  
		<tr>  
            <th><center><div class="col-md-12 form-group2 group-mail">
  <select name="i_name[]">
			
            	<option >Select</option>
				<?php while ($row1 = mysqli_fetch_array($run1)) {
   echo '<option value="'.$row1['itm_name'].'">'.$row1['itm_name'].'</option>';}?>

	
            </select>
			<div></center></th> 
			<th><center><INPUT TYPE="text" NAME="i_desc[]" PLACEHOLDER="Description" SIZE="30"></center></th> 
            
            <th><center><INPUT TYPE="text" NAME="i_qty[]" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate(this)" SIZE="30"></center></th> 
           
            <th><center><INPUT TYPE="text" NAME="i_rate[]" PLACEHOLDER="Rate" ID="rate" ONINPUT="calculate(this)" SIZE="30"></center></th> 
            <th><center><INPUT TYPE="text" NAME="i_amnt[]" PLACEHOLDER="Amount" ID="amnt" ></center></th> 
            <th></th>  

			
			
        </tr>
</TABLE>

			
            
				<div class="clearfix"> </div>
				
<div class="vali-form">
    <div class="col-md-6 form-group1 form-last">
              <label class="control-label">Subtotal</label>
              <input type="text" name="s_stotal" placeholder="" required="">
            </div>
                      

             <div class="col-md-6 form-group1 form-last">
              <label class="control-label">Discount</label>
              <input type="text" name="s_discount" placeholder="" required="">
            </div>
                     

            <div class="col-md-6 form-group1 form-last">
              <label class="control-label">Total</label>
              <input type="text" name="s_total" placeholder="" required="">
            </div>
            
             
            <div class="col-md-6 form-group1 form-last">
              <label class="control-label">Balance Due</label>
              <input type="text" name="s_bald" placeholder="" required="">
            </div>
            
          <div class="clearfix"> </div>
		 </div>

			
            <div class="col-md-12 form-group">
              <button type="submit" name="Submit" class="btn btn-primary">Submit</button>
              <button type="reset" class="btn btn-default">Reset</button>
            </div>
          <div class="clearfix"> </div>
          </div>
		  
            
        </form>

0

2 Answers 2

0

If I understood you correctly, the code you are looking for should look something like this:

var values = document.querySelectorAll('input.amnt'),//find all inputs  
                                                //that you need to add 
                                                //use regular dom selector 
                                                //like in css
    subtotal = 0;

for(var i = 0, ; = values.length; i<l; i++ ) {
    subtotal += values[i].value;
}

It'll always add all the vales in the documents, you can add or remove data, doesn't matter.

PS please do not use <center> tag - it's deprecated, you should be using css for that.

Sign up to request clarification or add additional context in comments.

4 Comments

please give full function
with function name and where to call this function
please tell me where should i place this?
It's just a snippet. Run it in the js console to see how it works so you understand how it works. If you understand how it works, you'll know where you want to put it in your application :)
0

A little something I put together after reading your issue. This still needs plenty of work doing to it but this should get you on the right lines.

I have added comments within the source code to explain step by step.

Add more will duplicate the contents of the table but this is just for demo use to show you can still trigger events with dynamic elements.

Discount will be deducted as a percent of the price.

$(document).on('input','.Calc',function(){
// Reset Total
var Total=0;
$('.Inputs').each(function(){
// Reset Price.
var Price=0;
// Reset Decution.
var Deduction=0;
//  Price x Quantity
Price=parseFloat($(this).find(".Qty").val())*parseFloat($(this).find(".Price").val());
var Percent=parseFloat($(this).find(".Disc").val());
  // If Discount is greater than 0 make deductions.
  if(Percent>0){
  // Calculate the discount Percent of the Price.
  // Example 300*40/100 = 120
  Deduction=Price*Percent/100;
  // Minus discount from the price.
  Price=Price-Deduction;
  }
// Sub total, add Price to existing Total
Total=Total+Price;
// Display Price and savings "£0 (Save £0)"
$(this).find("span").html('&pound;'+Price+' <small>(Save &pound;'+Deduction+')</small>');
});
// Display New Total.
$('#Total').html('Sub Total &pound;'+Total);
});

//--------- Clone / Append (Demo Use)
$('#More').on('click',function(){
// This is used to show you can run the functions even if the elements are dynamic. 
// (This is very messy but it shows that it works)
var target = document.getElementById('MyForm');
var tr = document.createElement('tr'); 
tr.setAttribute('class', 'Inputs'); // Edit this 
target.appendChild(tr);
var td1 = document.createElement('td');  
tr.appendChild(td1);
td1.innerHTML='Qty';
var td2 = document.createElement('td');  
tr.appendChild(td2);
td2.innerHTML='&pound;';
var td3= document.createElement('td');  
tr.appendChild(td3);
// Add inputs. 
td3.innerHTML='Discount:';
var QTY = document.createElement('input'); 
var PRICE = document.createElement('input'); 
var DISC = document.createElement('input'); 
QTY.setAttribute('type','text');
QTY.setAttribute('class','Qty Calc');
QTY.setAttribute('value',1);
PRICE.setAttribute('type','text');
PRICE.setAttribute('class','Price Calc');
PRICE.setAttribute('value',0);
DISC.setAttribute('type','text');
DISC.setAttribute('class','Disc Calc');
DISC.setAttribute('value',0);
td1.appendChild(QTY);
td2.appendChild(PRICE);
td3.appendChild(DISC);
td3.innerHTML=td3.innerHTML+'% <span></span>';
});
/* CSS for Demo Use. */
.Qty{width:30px;}
.Price{width:70px;}
.Disc{width:30px;}
span{color:red;font-weight:bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="More">Add</button>
<table id="MyForm">
<tr class="Inputs">
  <td>Qty<input type="text" class="Qty Calc" value="1"/></td>
  <td> &pound;<input type="text" class="Price Calc" value="0"/></td>
<td> Discount:<input type="text" class="Disc Calc" value="0"/>% <span></span></td>
</tr>
</table>
<span id="Total"></span>

If you have any questions about the source code above please leave a comment below and I will reply as soon as possible.

I hope this helps. Happy coding!

This is using jQuery

Update: Replaced clone() with createElement()

4 Comments

i need to give class of tr var row = document.createElement("TR");
your code works fine , since i am using other script to add row. for that subtotal dosent count amount
You can edit this to fit your needs. I can't work this into your existing source code without seeing this "Other script" Also your addRow() function will duplicate ID's. ID's should be unique / only used once.
@SannidhiBhadarka I have updated the answer to show you can also use document.createElement() just like you have in your current source code. It's down to you to add/edit this example to fit your existing source code. I don't do all the work for people, I just give them examples/working demos to build from. Keep in mind this still needs a lot of work and some cleaning up to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.