1

概要

  • JavaScriptで「個数」×「単価」の「小計」を出す注文フォームを作っています。
  • 注文は MySQL db に保存され、PHP 経由で取得されます。
  • 「単価」を手動で入力したいのですが、その数値を入力した後に乗算が行われることを望みます。
  • 10 行の項目 (配列) があります。
  • 記述されたすべてのコードは、期待どおりに正しく実行されます。

問題

  • 私の JavaScript 関数は最初の行に対してのみ実行され、他の行に対しては実行されません。
  • 項目タイプごとに、すべての行に対して実行したい。

マイコード

JS

function calc(){
    baseprice=parseInt(document.getElementById("baseprice").value);
    units=parseInt(document.getElementById("units").value);
    x=baseprice*units;
    document.getElementById("sub").value=x;
}

PHP/SQL

$alter=0;
//previous miscellaneous code
while($rows=mysql_fetch_array($sql))
{
    $alter=$alter+1;
 //edit       
$subCalc="<td><input name='units_".$alter."' id='units_".$alter."' type='hidden' value=".$rows['SUM(pizza_orders.qty)']."><input name='baseprice_".$alter."' id='baseprice_".$alter."' type='text' size='2' onchange='calc(this);'></td><td><input name='sub_".$alter."' id='sub_".$alter."' type='text' size='3'></td></tr>";

 //alternates the table row colour by modulus
    if ($alter %2 ==0){
        echo "<tr><td>".$rows['item_order']."</td>";
        echo "<td>".$rows['SUM(pizza_orders.qty)']."</td>".$subCalc;
    }else{
            echo "<tr class=\"alt\"><td>".$rows['item_order']."</td>";
            echo "<td>".$rows['SUM(pizza_orders.qty)']."</td>".$subCalc;
    }
}   

サンプル結果/状況

ここに画像の説明を入力

拡大

右下に総計を作成し、すべての小計フィールドを「onchange」として追加します。

subTotal=parseInt(document.getElementById("sub" + el.id.replace('baseprice', '')).value);                                                                                   document.getElementById("grandtotal")=  subTotal+parseInt(document.getElementById("grandtotal").value); 

デモ > JS フィドル

4

1 に答える 1

1

ID はページで一意である必要があります。ページに同じ ID を持つ複数の入力があります。したがって、最初の入力で計算を実行するたびにのみ実行されるのはなぜですか。各行を区別するために、「baseprice」と「units」の入力に数値を追加するのが最善の策です。さらに、「this」キーワードを calc 関数に渡して、関数をトリガーした要素を参照します。

行の例:

    <tr>
    <td>
    <input id="units_1" name="units_1" type="hidden" value="10" />
<!-- attach an onchange handler to baseprice_1, when a change is made trigger the calc function. -->
    <input id="baseprice_1" name="baseprice_1" type="text" onchange="calc(this);" />
    <input id="sub_1" name="sub_1" type="text" />
    </td>
    </tr>

JS:

/* An array to store the subtotals. */
grandTotalArr = [];

    function calc(el){
/* el = this (which is a reference to baseprice_1) */
        baseprice=parseInt(el.value);
        units=parseInt(document.getElementById("units" + el.id.replace('baseprice', '')).value);
        x=baseprice*units;
        document.getElementById("sub" + el.id.replace('baseprice', '')).value=x;

/* Store the subtotal in the grandTotalArr using it's id as the key. */
grandTotalArr["sub" + el.id.replace('baseprice', '')] = x;
/* Implode all values with the + operator, and evaluate as a JS expression. Once evaluated, update the grand total. */
document.getElementById('grand_total').value = eval(grandTotalArr.join('+'));
    }
于 2012-08-16T13:24:51.743 に答える