我尝试了一些代码,但没有成功。当下拉列表中的数量发生变化时,我的应付金额应该发生变化。因此,如果有人更改订单数量,则应乘以桌面的基数,结果应为总金额。这是我的代码的一部分,我认为与计算部分相关。
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
最佳答案
我找到了解决方案:
- 首先,删除此代码片段,因为它当前引发错误:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
- 第二,声明这两个变量来存储
<select>
标签元素与 futureselected
值如下:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
- 第三,添加此方法以获取
selected
值并乘以总数,如下所示:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
以下是完整的代码示例,供您引用:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
您还可以check this working code sample 。
如果您对代码有疑问,请告诉我。
关于javascript - 从下拉列表中选择不同选项后,如何计算应付金额的总值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584322/