【问题标题】:How to show total of dynamically added column using jquery如何使用 jquery 显示动态添加的列的总数
【发布时间】:2016-12-06 20:43:02
【问题描述】:

我制作了一个购物车,在其中添加了基于自动完成搜索的行。并根据数量价格变化。但我想找到小计的总数..我已经写了更新部分。但它显示的是 0 而不是实际值。谁能帮我找出我的 jQuery 代码有什么问题。谢谢!

 $('#searchName').autocomplete({
                source: '{!! asset('nameAutocomplete') !!}',
                select:function(suggestion,ui){
                    event.preventDefault();       
                        var $tbody = $('#example tbody');
                        $tbody.append('<tr><td class="id">' + ui.item.id +
                        '</td><td class="name">' + ui.item.value +
                        '</td><td class="price">' + ui.item.price +
                        '</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
                        $('.quantity').on('keyup',function(){
                            var tot = $(this).parent().prev().html() * this.value;
                           $(this).parent().next().find('.total').val(tot);  
                      console.log(calculateSum());    
                        });
                       function calculateSum(){
                        var sum = 0;
                    $(".total").each(function() {
                        var value = $(this).text();
                        // add only if the value is number
                        if(!isNaN(value) && value.length != 0) {
                            sum += parseFloat(value);
                        }
                        });
                    return sum;
                    }               
                   }                   
            });

这是表格部分:

<table  class="table table-striped table-bordered"  id="example">
                    <thead>
                      <tr>                      
                        <td>ID</td>
                        <td>Name</td>
                        <td>Price</td> 
                        <td>Quantity</td>
                        <td>Total</td>                     
                      </tr>
                    </thead>
                    <tbody>
                    </tbody>
                  </table>  

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    $(".total") 是一个输入,所以你应该使用var value = $(this).val();,而不是var value = $(this).text();

    【讨论】:

    猜你喜欢
    • 2011-09-05
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多