用于动态添加字段的javascript中的calulate函数

时间:2016-02-27 12:44:34

标签: javascript jquery html

我想计算表格的小计和总数

我尝试了一些javascripts,但dident为我工作

其中一些仅用于静态表,因为我正在添加动态行,但它们没有帮助

任何人都可以帮我添加脚本

式 1)小计=金额1 +金额2 + ... +金额(n) 2)总计=总计 - 折扣

这是我的代码

 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>

2 个答案:

答案 0 :(得分:0)

如果我理解正确,您正在寻找的代码应该是这样的:

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;
}

它总是会添加文档中的所有值,您可以添加或删除数据,不重要。

PS请不要使用<center>代码 - 它已被弃用,您应该使用css。

答案 1 :(得分:0)

阅读你的问题后,我把它放在一起。这仍然需要大量的工作,但这应该让你走在正确的位置。

我在源代码中添加了注释,逐步解释。

  

添加更多将复制表格的内容,但这仅供演示使用,以表明您仍然可以使用动态元素触发事件。

折扣将扣除价格的百分比。

$(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>

如果您对上述源代码有任何疑问,请在下面留言,我会尽快回复。

我希望这会有所帮助。快乐的编码!

这是使用jQuery

  

更新:用createElement()替换clone()