[英]Unable to print sum of function in js
我希望我的程序做什么:
我正在嘗試使用 html/java 腳本制作在線訂單。 在我的 select 元素中,有 3 個選項,每個選項都有不同的價格。 我試圖讓用戶 select 其中一個選項,選擇他們想要的數量,然后顯示總價。
問題
總價不會顯示。
我試過的
我已經在內部 js 腳本中創建,並創建了一個 function getChoice。 使用 if 語句,我正在檢查用戶選擇了哪個選項,並根據選擇的選項,將值的價格乘以他們想要的項目數量,並嘗試將該值返回到“總計”。
<script>
var choice = document.getElementById("burgerSize").value;
var amount = document.getElementById("quantity").value;
function(getTotalAmount){
if(choice === "4"){
document.getElementById("total").value=
amount*4;
}
if(choice === "6"){
document.getElementById("total").value=
amount*6;
}
if(choice === "10"){
document.getElementById("total").value=
amount*10;
}
}
</script>
我的 HTML 代碼:
Please select size:
<select id="burgerSize" onchange="getTotalAmount()">
<option disabled="disabled" selected = "selected" Select option</option>
<option value="4">Large </option>
<option value="6">Extra-Large </option>
<option value="10">Supersize </option>
</select>
<label for="quantity"> Quantity: </label>
<input type="number" id="quantity" name="quantity" min=1><br>
<label> Total cost: </label>
<input type="text" id ="total"/><br>
</form><br><br>
<script>
任何指向正確方向的指示都將不勝感激! 提前致謝
當用戶向輸入字段輸入值時,您可以通過調用 function 等方式輕松實現此功能。
function totalCal(){ const choice = document.getElementById("burgerSize").value; const amount = document.getElementById("quantity").value; document.getElementById("total").value = amount * choice; } document.getElementById("burgerSize").oninput = ( function(event) { totalCal(); }); document.getElementById("quantity").oninput = ( function(event) { totalCal(); });
<form> <label for="burgerSize">Please select size:</label> <select id="burgerSize"> <option disabled="disabled" selected="selected">Select option</option> <option value="4">Large </option> <option value="6">Extra-Large </option> <option value="10">Supersize </option> </select> <label for="quantity"> Quantity: </label> <input type="number" id="quantity" name="quantity" min=1><br> <label> Total cost: </label> <input type="text" id="total" /><br> </form>
如果在第一個option標簽末尾加上大於號(">")會更好,同時為了得到總值,可以按照本程序乘以amount和choice。
謝謝並致以最誠摯的問候!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.