2

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 column using JQuery. I am only getting the first row to display total when I enter values. Any help will be greatly appreciated.

     <script type="text/C#" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
         $(document).ready(function () {
            $(".txtMult").each(function () {
                $(this).keyup(function () {
                    multInputs();
                });
            });
           });

           function multInputs() {
               var mult = 0;
               $(".txtMult").each(function () {
                   var $val1 = $('#val1').val();
                   var $val2 = $('#val2').val();
                   var $total = ($val1 * 1) * ($val2 * 1)
                   $('#multTotal').text($total);
               });
           }

    </script>
    @using (@Html.BeginForm())
    {
        <table>
        <tr>
            <th>
                Quanity
            </th>
            <th>
                Unit Price
            </th>
            <th>
                Total
            </th>
        </tr>
        @for (int i=0; i < 5; i++)
        {

            <tr>
                <td>
                    <input class ="txtMult" name="txtEmmail" id="val1"  />
                </td>
                <td>
                    <input class ="txtMult" name="txtEmmail" id="val2"/>
                </td>
                <td>
                    <span id="multTotal">0.00</span>
                </td>
            </tr>

    }
<tr>
    <td colspan="3" align="right">
        Grand Total# <span id="grandTotal">0.00</span>
    </td>
</tr>
    </table> 
    }

enter image description here

2 Answers 2

8

Your html is invalid: the id attribute is supposed to be unique but you are repeating the same three ids in every row. The easiest way to fix this is to change your inputs to have class="val1" and class="val2" instead of id="val1" and `id="val2", and change your row total to have class="multTotal". I'd also move the txtMult class to each of the tr elements with the inputs in them, for ease of selecting those rows:

        <tr class="txtMult">
            <td>
                <input name="txtEmmail" class="val1"  />
            </td>
            <td>
                <input name="txtEmmail" class="val2"/>
            </td>
            <td>
                <span class="multTotal">0.00</span>
            </td>
        </tr>

...and then change the selector in your jQuery code to select by class in the context of the current row. Note also that you don't need an .each() loop to bind the .keyup() handlers to the elements that match your selector, just use $("someselector").keyup():

 $(document).ready(function () {
       $(".txtMult input").keyup(multInputs);

       function multInputs() {
           var mult = 0;
           // for each row:
           $("tr.txtMult").each(function () {
               // get the values from this row:
               var $val1 = $('.val1', this).val();
               var $val2 = $('.val2', this).val();
               var $total = ($val1 * 1) * ($val2 * 1);
               // set total for the row
               $('.multTotal', this).text($total);
               mult += $total;
           });
           $("#grandTotal").text(mult);
       }
  });

Working demo: http://jsfiddle.net/nnnnnn/5FpWC/

Sign up to request clarification or add additional context in comments.

2 Comments

I think I can't use two class on a same input <input class ="txtMult" name="txtEmmail" class="val1" /> What would be the best way to fix this?
You can use two or more classes on the same element, just separate the class names with spaces within a single class attribute: <input class="txtMult val1 otherclass etc" name="txtEmmail">. Note though that in my solution I removed the txtMult class from the inputs and put it on the tr elements (you could still target the inputs in your stylesheet by using a selector of tr.txtMult input - which says 'select any inputs that are descendants of tr elements with "txtMult" class').
1

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)

2 Comments

Note that you don't need parseFloat() for things that are already numbers, i.e., you don't need to use it on your total variable and you don't need to use it on $(m[0]).val()*$(m[1]).val() because the * operator converts both operands to numbers.
you are right about total. but $(m[0]).val()*$(m[1]).val() is parsed to show the result up to two decimal point when given input is integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.