JQuery multiply input values of table rows

后端 未结 2 2005
挽巷
挽巷 2021-01-03 16:28

I want to calculate each row\'s total price by multiplying individual row\'s inputs and then finally calculate a grand total by adding all the total values of the Total colu

2条回答
  •  一生所求
    2021-01-03 16:50

    Let add a class in to the table.

    At first add a change event to all inputs of the table. On change of a input field multiply all inputs of same row and update the multTotal and grandTotal

    $(function(){
                $('.in input').change(function(){
                    var p=$(this).parent().parent() //get the parent of changed input
                    var m=p.find('input.txtMult') //find all input of the row
                    var mul=parseFloat($(m[0]).val()*$(m[1]).val()).toFixed(2) //multiply them
                    var res=p.find('.multTotal') // get corresponding multTotal
                    res.html(mul); //show the result
                    var total=0;
                    $('.in .multTotal').each(function(){
                        total+=parseFloat($(this).html())
                    }) //calculate grand total
                    $('.in #grandTotal').html(parseFloat(total).toFixed(2)) //show grand total
                });
            })
    

    check this at jsfiddle

    If need to process more than 2 fields change

    var mul=parseFloat($(m[0]).val()*$(m[1]).val()).toFixed(2) //multiply them
    

    to

    var mul=1;
    $(m).each(function(){
      mul*=$(this).val()
    })
    mul=parseFloat(mul).toFixed(2)
    

提交回复
热议问题