我是javascript的新手,热衷于学习。
我目前有一个表格,允许用户选择食物,输入数量并计算价格。
每当我更改所选食物时,我的功能都能动态计算价格。但是,如果我选择重新输入其他数量,价格将不会动态更新。我尝试这样做,以便每当我改变食物下降或数量值时,价格都会动态更新。感谢任何帮助。
谢谢。
附上我的代码。
function getSelectValue() {
var selectedValue1 = document.getElementById("dropdownList").value;
if (selectedValue1 === 'Carbonara') {
var currentPrice1 = 4.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
} else {
var currentPrice1 = 3.50 * parseFloat(amount_1.value);
document.getElementById("price_1").value = "$" + currentPrice1;
}
var selectedValue2 = document.getElementById("dropdownList2").value;
if (selectedValue2 === 'Carbonara') {
document.getElementById("price_2").value = "4.50";
var currentPrice2 = 4.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "$" + currentPrice1;
} else {
var currentPrice2 = 3.50 * parseFloat(amount_2.value);
document.getElementById("price_2").value = "3.50";
}
}

Select Food:
<select id="dropdownList" name="dropdownList" onchange="getSelectValue();">
<option value="Prawn Aglio Olio">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_1">
<br>
Price per unit:
<input type="text" id="price_1" value="" disabled>
<br>
<br>
<!-- Second Selection -->
Select Food:
<select id="dropdownList2" name="dropdownList2" onchange="getSelectValue();">
<option value="">Prawn Aglio Olio</option>
<option value="Carbonara">Carbonara</option>
</select>
<br>
Select Quantity:
<input type="text" id="amount_2">
<br>
Price per unit:
<input type="text" id="price_2" value="" disabled>
<br>
<input type ="button" value="Submit">
<a href="vendor.jsp">
<input type="button" value="Back">
</a>
</form>
&#13;
答案 0 :(得分:0)
尝试在数量
的输入中写入相同的事件(getSelectedValue())尝试初始化所有变量,以便一切都更清晰
检查输入element.value&#34; Quanity&#34;如果存在,请填写“价格”字段
测试此
import axios from 'axios'
&#13;
function getSelectValue() {
var dropdownList = document.getElementById("dropdownList");
var price_1 = document.getElementById("price_1")
var amount_1 = document.getElementById("amount_1");
var dropdownList2 = document.getElementById("dropdownList2");
var price_2 = document.getElementById("price_2");
var amount_2 = document.getElementById("amount_2");
var currentPrice1 = "$" + 0;
var currentPrice2 = "$" + 0;
if (amount_1.value) {
if (dropdownList.value === 'Carbonara') {
currentPrice1 = 4.50 * parseFloat(amount_1.value);
} else {
currentPrice1 = 3.50 * parseFloat(amount_1.value);
}
price_1.value = "$" + currentPrice1;
}
if (amount_2.value) {
if (dropdownList2.value === 'Carbonara') {
currentPrice2 = 4.50 * parseFloat(amount_2.value);
} else {
currentPrice2 = 3.50 * parseFloat(amount_2.value);
}
price_2.value = "$" + currentPrice2;
}
}
&#13;