1

I want to change the sum price when I change the quantity. This is view:

@foreach (var item in Model)
                    {
                        <tr>
                            <td>@item.Product.Name</td>
                            <td><input type="number" value="@item.Count" id="Count" /></td>
                            <td id="Price">@item.Product.Price</td>
                            <td id="SumPrice">@item.SumPrice</td>
                       </tr>
                    }

This is the java script that I used but it doesn't work. When I change the quantity the sum price doesn't change.

 $('#Count').on('keyup',function(){
    var tot = $('#Price').val() * this.value;
    $('#SumPrice').val(tot);
});
niki tmb
  • 177
  • 1
  • 14

1 Answers1

0

You cannot use same ids for mutliple elements instead use class. Then , using $(this).closest("tr") get closest tr reference and use .find to get the value of td which you needed to calculate.

Demo Code :

$('.Count').on('keyup change', function() {
  //get closest tr -> find price class get value
  var tot = $(this).closest("tr").find('.Price').text() * this.value;
  $(this).closest("tr").find('.SumPrice').text(tot); //set value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Abc</td>
    <!--added class-->
    <td><input type="number" value="1" class="Count" /></td>
    <td class="Price">21</td>
    <td class="SumPrice">21</td>
  </tr>
  <tr>
    <td>Xyz</td>
    <td><input type="number" value="1" class="Count" /></td>
    <td class="Price">12</td>
    <td class="SumPrice">12</td>
  </tr>
</table>
Swati
  • 28,069
  • 4
  • 21
  • 41
  • Thank you :) It worked. But can you please tell me why I can't use the same Ids? – niki tmb Nov 08 '20 at 13:16
  • Have a look at [this](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) .Also , [this](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) post will help to understand more :) – Swati Nov 08 '20 at 13:21