简体   繁体   English

使用jQuery的输入框中的值总和不起作用

[英]sum of values in input boxes using jquery not working

I am creating a form that takes values from a hash and creates three input boxes(having class amount, acNo,debNo) per key name attribute combination of the hash value and a string bed in my case now i am trying to get the sum of the values in input boxes having "bed" in their name and have class "amount". 我正在创建一个从哈希中获取值表单,并在我的情况下为哈希值和字符串床的每个键名属性组合创建三个输入框(具有金额,acNo,debNo),现在我想获取输入框中名称中带有“ bed”且类别为“ amount”的值。

 $(document).ready(function(){
 alert('document is loaded');
    $("input[name*='bed'][class='amount']").each(function() {//doen't go in this loop

        alert('in the bed'); //no alert
            $(this).keyup(function(){

                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;
        //iterate through each textboxes and add the values
        $("input[name*='bed'][class='amount']").each(function() { 
            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $("input[name='totalBEDamount']").val(sum.toFixed(2));
    }

I am using the above jquery to get sum of values. 我正在使用上面的jQuery来获取值的总和。 The problem is that it works fine as fixed layout fixed layout fiddle but when i am creating the document on radio button selection from a hash the code fiddle with error doesn't work? 问题是它可以像固定布局固定布局小提琴一样工作,但是当我从哈希中选择单选按钮创建文档时, 带有错误的代码小提琴不起作用? Why??? 为什么???

Use [class='amount'] and use on() (for your dynamically created elements ) in place of [class='column'] like, 使用[class='amount']并使用on() (用于动态创建的元素 )代替[class='column']例如,

$(document).ready(function () {
     $(document).on('keyup',"input[name*='bed'][class='amount']", function () {
         var sum = 0;
         //iterate through each textboxes and add the values
         $("input[name*='bed'][class='amount']").each(function () {
             //add only if the value is number
             if (!isNaN(this.value) && this.value.length != 0) {
                 sum += parseFloat(this.value);
             }

         });
         $("input[name='totalBEDamount']").val(sum.toFixed(2));
     });
});

Working Demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM