本文介绍了在JavaScript中为动态添加的字段计算函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的表单计算小计和总额

我试过一些javascript,但是dident为我工作



它们中的一些仅适用于静态表,因为我添加了动态行,它们并不是很有帮助的。

可以帮助我添加脚本。



公式
1)小计= amount1 + amount2 + ... + amount(n)
2)total = total - discount

这里是我的代码

 < form action =<?php echo用htmlspecialchars($ _ SERVER [ PHP_SELF]);?>中method =post> < H3>添加新购买< / h3> < div class =vali-form> < div class =col-md-3 form-group2 group-mail> < select required name =s_account> < option>  - 选择帐户名称 - < / option> <?php while($ row = mysqli_fetch_array($ run)){echo'< option value =''。$ row ['acc_name']。'>'。$ row ['acc_name']。'< ; /选项>';}>?; < /选择> < / DIV> < div class =clearfix> < / DIV> < div class =col-md-4 form-group1 form-last> < label class =control-label>提醒< / label> < input type =textname =s_remplaceholder =required => < / DIV> < div class =col-md-4 form-group1 group-mail> < label class =control-label>发票日期< / label> < input type =datename =s_idateclass =form-control1 ng-invalid ng-invalid-requiredng-model =model.dateplaceholder =required => < / DIV> < div class =col-md-4 form-group1 group-mail> < label class =control-label>到期日期< / label> < input type =datename =s_ddateclass =form-control1 ng-invalid ng-invalid-requiredng-model =model.daterequired => < / DIV>< / DIV> < div class =clearfix> < / DIV> < div class =col-md-12 form-group1 form-last> < div class =table-responsive> < TABLE ID =tblPetsclass =table table-striped table-bordered table-hover>< tr> < th>中心>项目名称< / center>< / th> <的第i;<中心],[说明与LT; /中心],[< /第> <的第i;<中心],[。数量< /中心],[< /第> <的第i;<中心],[数< /中心],[< /第> <的第i;<中心],[度< /中心],[< /第> < th>< center>< INPUT TYPE =ButtononClick =addRow('tblPets')VALUE =Add Row>< / center>< / th> < / TR> < TR> < th>中心>< div class =col-md-12 form-group2 group-mail> < select name =i_name []> < option>选择< / option> <?php while($ row1 = mysqli_fetch_array($ run1)){echo'< option value =''。$ row1 ['itm_name']。'>'。$ row1 ['itm_name']。'< ; /选项>';}>?; < /选择> < DIV>< /中心],[< /第> < th>< center>< INPUT TYPE =textNAME =i_desc []PLACEHOLDER =DescriptionSIZE =30>< / center>< / th> < th>中心< INPUT TYPE =textNAME =i_qty []PLACEHOLDER =QTYID =qtyONINPUT =calculate(this)SIZE =30>< /中心],[< /第> < th>中心< INPUT TYPE =textNAME =i_rate []PLACEHOLDER =RateID =rateONINPUT =calculate(this)SIZE =30>< /中心],[< /第> < th>< center>< INPUT TYPE =textNAME =i_amnt []PLACEHOLDER =AmountID =amnt>< / center>< / th> <的第i;< /第> < / TR>< /表> < div class =clearfix> < / DIV> < div class =vali-form> < div class =col-md-6 form-group1 form-last> < label class =control-label>小计< / label> < input type =textname =s_stotalplaceholder =required => < / DIV> < div class =col-md-6 form-group1 form-last> < label class =control-label>折扣< / label> < input type =textname =s_discountplaceholder =required => < / DIV> < div class =col-md-6 form-group1 form-last> < label class =control-label> Total< / label> < input type =textname =s_totalplaceholder =required => < / DIV> < div class =col-md-6 form-group1 form-last> < label class =control-label>余额到期< / label> < input type =textname =s_baldplaceholder =required => < / DIV> < div class =clearfix> < / DIV> < / DIV> < div class =col-md-12 form-group> < button type =submitname =Submitclass =btn btn-primary>提交< / button> < button type =resetclass =btn btn-default>重设< / button> < / DIV> < div class =clearfix> < / DIV> < / DIV> < / form>  

解决方案



我已经在源代码中添加了一些注释来逐步解释。

p>

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



  $(document).on('input','。Calc',function(){// Reset Totalvar Total = 0; $ ('.Inputs')。each(function(){// Reset Price.var Price = 0; // Reset Decution.var Deduction = 0; // Price x QuantityPrice = parseFloat($(this).find(。 ().val())* parseFloat($(this).find(。Price).val()); var Percent = parseFloat($(this).find(。Disc).val() ); //如果折扣大于0,则扣除if(Percent> 0){//计算折扣价格百分比//例300 * 40/100 = 120扣除=价格*百分比/ 100; //价格=价格扣除;} //总计,将价格添加到现有TotalTotal =总价+价格; //显示价格和储蓄£(this).find($ (& pound;'+ Price +'< small>(Save& pound;'+ Deduction +')< / small>');}); // Display New Total。 '#合计')。HTML ('Sub Total& pound;'+ Total);}); // --------- Clone / Append(Demo Use)$('#More')。on('click',function ){//这用于显示即使元素是动态的,也可以运行这些函数。 //(这很杂乱,但它表明它的工作原理)var target = document.getElementById('MyForm'); var tr = document.createElement('tr'); tr.setAttribute('class','Inputs'); //编辑这个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); //添加输入。 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演示使用。 * /数量{宽度:30像素;}价格{宽度:70像素;}。光盘{宽度:30像素;}跨度{颜色:红;字型重量:粗体;} < 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 =textclass =Qty Calcvalue =1/>< / td> < TD> & pound;< input type =textclass =Price Calcvalue =0/>< / td>< td>折扣:< input type =textclass =Disc Calcvalue =0/>%< span>< / span>< / td>< / tr>< / table>< ; span id =Total>< / span>

$ b

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



我希望这有助于您。快乐的编码!



这是使用jQuery
$ b


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

formula1) 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>

解决方案

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.

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

这篇关于在JavaScript中为动态添加的字段计算函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:54