计算使用jquery动态添加输入字段的总和 [英] Calculate sum of dynamically adding input fields with jquery

查看:54
本文介绍了计算使用jquery动态添加输入字段的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,用于计算金额之和.行是使用jquery clone()动态生成的;

I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

这段代码正在计算渲染行的总和,而不是新创建的行

This code is calculating sum of rendered rows not the new created rows

 $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));


        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        }); 
});

推荐答案

  1. var $inst = $('.inst_amount');移至使用位置:
    var total = 0,$inst = $('.inst_amount');-实际上甚至没有.查看我的代码

  1. move var $inst = $('.inst_amount'); to where you use it:
    var total = 0,$inst = $('.inst_amount'); - actually don't even. See my code

使用逗号分隔变量

干-不要重复自己

正确提供该类,然后将该字段添加到容器中.

give the class correctly and add the field to a container.

function sumIt() {
  var total = 0, val;
  $('.inst_amount').each(function() {
    val = $(this).val();
    val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
    total += val;
  });
  $('#total_price').html(Math.round(total));
  $('#total_amount').val(Math.round(total));
}

$(function() {

  // $('.datepicker').datepicker(); // not needed for this test


  $("#add").on("click", function() {
    $("#container input").last()
      .before($("<input />").prop("class","inst_amount").val(0))
      .before("<br/>");
    sumIt();  
  });


  $(document).on('input', '.inst_amount', sumIt);
  sumIt() // run when loading
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
  <input type="text" class="inst_amount" value="4" /><br/>
  <input type="text" class="inst_amount" value="" /><br/>
  <input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span>

这篇关于计算使用jquery动态添加输入字段的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆