2017-02-01 8 views
1

各行の2列の乗算が必要です。これは私のコードとスクリプトです。このスクリプトは機能していますが、ちょうど最初の行のために、このスクリプトの出力は次のようになります。jQueryで2列の乗算

enter image description here

2行目の結果が間違っている:

<form> 
<table id="my-table"> 
    <?php 
    $query3 = mysqli_query($con,"select * from orders") or die("sdfsfs"); 
    while($row3=mysqli_fetch_array($query3)) 
    { 
     $quantity = $row3['quantity']; 
     $unit_price = $row3['unit_price']; 
     //$total = $quantity * $unit_price; 
    ?> 
     <tr> 
      <td><input type="text" class="common quantity" name="1" id="quant" value="<?php echo $quantity; ?>"></td> 
      <td><input type="text" class="common price" name="2" id="units" value="<?php echo $unit_price; ?>"></td> 
      <td><input type="text" class="total" name="3" id="total" readonly></td> 
     </tr> 
<?php } ?> 
     <tr> 
      <td colspan="2"><label class="form-control">Subtotal</label></td> 
      <td><input name="subtotal" readonly id="subtotal" class="sub" type="text" /></td> 
     </tr> 
</table> 
</form> 

jQueryの

<script> 
     $(".total").each(function() { 
     $('.total').val(parseFloat($('#quant').val()) * parseFloat($('#units').val())); 
     }); 
</script> 
+0

あなたは 'idは=「合計」を持っています'/' id = "quant" '... while whileループ - *間違い*。 IDは一意でなければならない – Justinas

答えて

2

反復してIDを交換してください:

$("#my-table tr:not(:last)").each(function() { 

    $(this).find('.total').val(parseFloat($(this).find('.quantity').val()) * parseFloat($(this).find('.price').val())); 
    }); 

}); 
+0

ありがとう@Norlihazmeyそれは働いている。 :) –

+0

それを聞いてうれしいとあなたを歓迎するメイト –

2

これは、すべての行で同じIDを持つためです。そのため、コードでは常にそのIDが最初に出現するため、常に最初の行の値のみが計算されます。それ以外の場合にのみマッチした最初だけ取るのクラスの代わりにIDの列と使用クラス以上

$(document).ready(function() { 
 
    $('.quantity, .price').change(function() { 
 
    var parent = $(this).closest('tr'); 
 
    parent.find('.total').val(parseFloat(parent.find('.quantity').val()) * parseFloat(parent.find('.price').val())) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td> 
 
     <input type="text" class="common quantity quant" name="1"> 
 
    </td> 
 
    <td> 
 
     <input type="text" class="common price units" name="2"> 
 
    </td> 
 
    <td> 
 
     <input type="text" class="total" name="3" class="total" readonly> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" class="common quantity quant" name="1"> 
 
    </td> 
 
    <td> 
 
     <input type="text" class="common price units" name="2"> 
 
    </td> 
 
    <td> 
 
     <input type="text" class="total" name="3" class="total" readonly> 
 
    </td> 
 
    </tr> 
 
</table>

+0

私はしたが動作しなかった –

+0

@AfzalKhanまた、 'this'の代わりに' .total'の値を適用する – Justinas

+0

助けてくれてありがとう、私は答えを持ってくれた: –