如何使用javascript计算php for loop值

时间:2015-03-17 10:12:59

标签: javascript php

我已经在forloop中显示了一些值。我想计算这些值并将其添加到textbox中。这是我的代码

<?php
 $itemCount = count($_POST["opt"]);
 for($i=0;$i<$itemCount;$i++) {
        $op_name=$_POST['opt'][$i];
        $price=$_POST['price'][$i];
?>
 <tr>
     <td><input type="text" value="<?php echo $op_name;?>" name="opt" /></td>
     <td><input type="text" value="<?php echo $price;?>" name="price" id="price" style="width: 40px;" onkeyup="order()"/></td>
     <td><input type="text" name="amt" style="width: 40px;" id="amount" onkeyup="order()" /></td>
 </tr>

 <?php
    }
 ?>
Total <input type="text" value="<?php echo $tot;?>" id="tot" />onkeyup="order()"/>

的javascript

function order(){
    var price=document.getElementById("price").value;
    var amt=document.getElementById("amount").value;
    var cal_price=1*price;
    var cal_amt=1*amt;
    document.getElementById("tot").value =((cal_price)*(cal_amt));
    }

我的代码只计算第一行的值。我希望所有Price * ammount总数显示在文本框中

enter image description here

1 个答案:

答案 0 :(得分:4)

  1. ID必须是唯一的。
  2. 如果您使用[]命名字段(例如name="price[]"),PHP会将您的字段作为数组处理。
  3. 使用document.getElementsByName("price[]")获取价格字段的集合
  4. 喜欢这个

    &#13;
    &#13;
    function order() {
      var prices = document.getElementsByName("price[]");
      var amts = document.getElementsByName("amt[]");
      var total = 0;
      for (var i = 0; i < prices.length; i++) {
        var cal_price = 1 * prices[i].value; // or parseFloat(prices[i].value)
        var cal_amt = 1 * amts[i].value; // or parseInt(amts[i].value,10)
        total += cal_price * cal_amt;
      }
      document.getElementById("tot").value = total.toFixed(2);
    }
    &#13;
    <table>
      <tr>
        <td><input type="text" value="" name="opt[]" /></td>
        <td><input type="text" value="1.5" name="price[]" style="width: 40px;" onkeyup="order()" /></td>
        <td><input type="text" name="amt[]" style="width: 40px;" onkeyup="order()" /></td>
      </tr>
      <tr>
        <td><input type="text" value="" name="opt[]" /></td>
        <td><input type="text" value="2.5" name="price[]" style="width: 40px;" onkeyup="order()" /></td>
        <td><input type="text" name="amt[]" style="width: 40px;" onkeyup="order()" /></td>
      </tr>
      <tr>
        <td><input type="text" value="" name="opt[]" /></td>
        <td><input type="text" value="3.25" name="price[]" style="width: 40px;" onkeyup="order()" /></td>
        <td><input type="text" name="amt[]" style="width: 40px;" onkeyup="order()" /></td>
      </tr>
    </table>
    <input type="text" id="tot" />
    &#13;
    &#13;
    &#13;