Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript动态添加的只读输入框的总和_Javascript_Jquery_Html - Fatal编程技术网

使用javascript动态添加的只读输入框的总和

使用javascript动态添加的只读输入框的总和,javascript,jquery,html,Javascript,Jquery,Html,我试图计算所有输入框的值之和 <input class='total' type='number' name='total[]' readonly> 这是因为只有在用户更改文本框中的值时才会引发“更改”事件,而不是在DOM操作更改该值时。您可以通过更新总文本框来触发计算 $("#InputsWrapper").on('change', '.discount',function(){ var tr = $(this).closest('tr'); var qua

我试图计算所有输入框的值之和

<input class='total' type='number' name='total[]' readonly>

这是因为只有在用户更改文本框中的值时才会引发“更改”事件,而不是在DOM操作更改该值时。您可以通过更新总文本框来触发计算

 $("#InputsWrapper").on('change', '.discount',function(){
     var tr = $(this).closest('tr');
     var quantity=tr.find(".qty").val();
     var percent=tr.find(".discount").val();
     var price=tr.find(".price").val();
     var tprice = price * quantity
     var discountpercent=percent / 100;
     var discountprice=(tprice * discountpercent );

     tr.find(".total").val(tprice - discountprice);
     calculateTotals()
});

function calculateTotals()
{
    var $summands = $('#invEntry').find('.total');
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $('#totaldp').val(sum);
}

在tr行中添加一个ID或者使用一个隐藏字段来存储项目计数器不是更好吗。(您想知道发票上有多少项是正确的吗?)?我是JS新手。您可以将$form.delegate('.total','click',function()重命名为标准函数(例如称为calculateTotals),并从$(“#InputsWrapper”)调用它。on('change','discount',function()){如果使用knockout.js将UI绑定到一组javascript对象,那么与事件相关的代码就会少得多。下面是一个js文档,介绍了它的工作原理:
 $("#InputsWrapper").on('change', '.discount',function(){
     var tr = $(this).closest('tr');
     var quantity=tr.find(".qty").val();
     var percent=tr.find(".discount").val();
     var price=tr.find(".price").val();
     var tprice = price * quantity
     var discountpercent=percent / 100;
     var discountprice=(tprice * discountpercent );

     tr.find(".total").val(tprice - discountprice);
     calculateTotals()
});

function calculateTotals()
{
    var $summands = $('#invEntry').find('.total');
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $('#totaldp').val(sum);
}