user4398229
user4398229

Reputation:

Multiply two textbox inside loop and display result on third textbox

This code will result for 10 lines of textbox1, textbox2, and textbox3. If I enter value in first line of textbox which is in loop1. for example 1 and 3 it will multiply and result is 3 . but then it will display the result in all loop. How can i make it only in loop1.?

Example

        QTY    PRICE   AMOUNT

line1    1        2      3
line2                    3
line3                    3
line4                    3
line5                    3
line6                    3
line7                    3
line8                    3
line9                    3
line10                   3

PHP HTML CODE

<?php for($x=1; $x<=10; $x++){?>
<tr> 
    <td><input type="text" name="qty<?=$x;?>" class="qty form-control" size="6"/></td>
    <td><input type="text" name="price<?=$x;?>" class="price form-control" /></td>
    <td><input type="text" name="amount<?=$x;?>" class="amount form-control"></td>
</tr>
<?php } ?>

JS CODE

<script>
    $(".price,.qty").keyup(function () {
      $('.amount').val($('.qty').val() * $('.price').val());
    });
</script>

Upvotes: 0

Views: 1349

Answers (3)

user4398229
user4398229

Reputation:

I solve it .. I just change it instead of using Class I use ID then put variable x inside the id and also put variable x on my JS

<?php for($x=1; $x<=10; $x++){?>
<tr> 
   <td><input type="text" name="qty<?=$x;?>" id="qty<?=$x;?>" class="form-control" size="6"/></td>
   <td><input type="text" name="price<?=$x;?>" id="price<?=$x;?>" class="orm-control" /></td>
   <td><input type="text" name="amount<?=$x;?>" id="amount<?=$x;?>" class="form-control"></td>
</tr>
<?php } ?>


$("#price<?=$x;?>,#qty<?=$x;?>").keyup(function () {
 $('#amount<?=$x;?>').val($('#qty<?=$x;?>').val() * $('#price<?=$x;?>').val());
});

Upvotes: 0

Ayyanar G
Ayyanar G

Reputation: 1545

this will be much easy if you write separate for each event try this,

  <script>
 $(document).ready(function(){
        $(".qty").keyup(function () {
        $(this).closest('tr').find('.amount').val($(this).val() *    $(this).closest('tr').find('.price').val());
    });    

     $(".price").keyup(function () {
      $(this).closest('tr').find('.amount').val($(this).closest('tr').find('.qty').val() * $(this).val());
    }); 
}); 
</script>

Upvotes: 2

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

<script>
    $(".price,.qty").keyup(function () {
        var curName = $(this).attr('name');
        var reqName = '';

        if (curName.indexOf("qty") != -1) {
         reqName = curName.substr(3);
        } else {
          reqName = curName.substr(5);
        }
        $("input[name='amount"+reqName+"']").val($("input[name='qty"+reqName+"']").val() * $("input[name='price"+reqName+"']").val());
    });
</script>

Upvotes: 0

Related Questions