2012-02-12 40 views
1

我使用动态添加的域创建表单并想总结所有添加的域。到目前为止,我有以下的代码,但它只是总结的第一行:在动态添加的表单域中使用jquery.calculation.js

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <title>Totals</title> 
    <script type="text/javascript" src="../js/jquery/jquery-1.6.2.js"></script> 
    <script type="text/javascript" src="../js/jquery/jquery.calculation.js"></script> 

    <script type="text/javascript"> 
    //Sum 
    $(document).ready(
     function(){ 
      $('input[name^=reds]').sum("keyup", "#totalSumReds"); 
      $("input[name^=blues]").sum("keyup", "#totalSumBlues"); 
     }   
    ); 
    </script> 

    <script type="text/javascript"> 
    //Add/remove form fields 
    jQuery(function($){ 
     $('#btnAdd').click(function(){ 
      var num = $('.clonedInput').length; 
      var newNum = new Number(num + 1); 
      var newElem = $('#input' + num).clone().attr('id', 'input' + newNum); 

      newElem.children(':first').attr('id', 'name' + newNum).attr('reds', 'reds' + newNum); 
      $('#input' + num).after(newElem); 
      $('#btnDel').attr('disabled', false); 
      if (newNum == 5) 
       $('#btnAdd').attr('disabled', 'disabled'); 
     }); 

     $('#btnDel').click(function() { 
      var num = $('.clonedInput').length; 
      $('#input' + num).remove(); 
      $('#btnAdd').attr('disabled', false); 
      if (num-1 == 1) 
       $('#btnDel').attr('disabled', 'disabled'); 
     }); 

     $('#btnDel').attr('disabled', 'disabled'); 
    }); 
    </script> 
</head> 

<body> 
<form id="myForm"> 
    <div id="input1" style="margin-bottom:4px;" class="clonedInput"> 
     Numbers: <input type="text" name="reds"/> 
     <input type="text" name="blues" id="blues"/> 
    </div> 
<div> 
     Totals: <input type="text" name="totalSumReds" id="totalSumReds" value="" size="2" readonly="readonly" /> 
     <input type="text" name="totalSumBlues" id="totalSumBlues" value="" size="2" readonly="readonly" /> 

</div> 
    <div> 
     <input type="button" id="btnAdd" value="add line" /> 
     <input type="button" id="btnDel" value="remove line" /> 
    </div> 
</form> 
</body> 
</html> 

什么,我应该尝试修复它的任何想法?谢谢!

+0

我不认为你应该使用这种类似的'变种newNum =新的Number(NUM + 1);' – elclanrs 2012-02-12 22:36:34

回答

0

在您的代码中,您只在现有输入字段中注册求和功能,随后添加的任何字段都不会触发计算,并且在求和时也不会被考虑。

你可以使用事件代表团来代替:

<script type="text/javascript"> 
    // Sum 
    $(function(){ 
     $('#myForm').live("keyup", "input[name^=reds]", function() { 
      var sum = $('input[name^=reds]').sum(); 
      $('#totalSumReds').val(sum); 
     }); 
     $('#myForm').live("keyup", "input[name^=blues]", function() { 
      var sum = $('input[name^=blues]').sum(); 
      $('#totalSumBlues').val(sum); 
     }); 
    }); 
</script> 
+0

谢谢!它按预期工作。 – 2012-02-13 03:02:36

+0

如果您喜欢此解决方案,请将答案标记为已接受,谢谢。 – 2012-02-13 09:01:23