2

数量/単位を追加し、消費税を表示する合計を生成するスクリプトを作成しました。

GST (10% の売上税) が計算されて追加される前に、この電卓で #discount を認識して合計から差し引くにはどうすればよいですか?

また、ページの読み込み時に合計を生成することは可能ですか? ユーザーが「合計を生成」ボタンを押す代わりに?

HTML

<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>


<input type="button" value="Generate Total" onclick="total()"  /><br><br>

Discount <input type="text" id="discount" name="discount" value="500"/><br><br>

Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />

JS

function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");

for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
    continue;
}
total_value += parseFloat(all_others[i].value);
}

document.getElementById("units_total").value = (total_value).toFixed(1);

document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);

document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);

document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
4

2 に答える 2

1

まず、ウィンドウの読み込み時に関数を実行するには、load イベントでラップします。

window.onload = function() {
    total();
}

第二に、それを割引で計算するには、変数を数回変更するだけで済みますが、それらを一緒に追加するときは、必ず次のように解析してください.parseFloat()

if (document.getElementById('discount').value != '') {
    var discount = document.getElementById('discount').value;
}
else {
    var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);

document.getElementById("sub_total").value = sub_total;

document.getElementById("gst_total").value = gst;

document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);

デモ

于 2012-09-20T02:32:45.293 に答える
0

まず、サーバー側とクライアント側の両方で検証と計算を実行することをお勧めします。1 つ目はセキュリティを確保し、2 つ目は UI の応答性を向上させます。

そうは言っても、いくつかのサポート変数を導入して、それらに対して計算を実行する方がよいでしょう。使用したい要素から値を取得しgetElementById、変数に格納する必要があります。次に、その変数に対して計算を実行し、最終的に結果をユーザーに表示するために使用する要素に配置する必要があります。

ページの読み込み時に操作を実行するには、これを見てください。

于 2012-09-20T02:15:32.757 に答える