所以我有这个复选框:
<input type="checkbox" id="extra-bathroom" name="extra-bathroom" value= "1" style="display: inline;" onchange="updatePrice();">Extra bathroom?
我的功能很好。我正在研究如何通过添加来更新以下输入的值(我知道我只能更改值,但我想通过添加来实现)
<input id="total-price" type="button" value= 0 style="width: 100%; margin-top: 5px;">
当前的JS:
window.updatePrice = function () {
if (document.getElementById('extra-bathroom').checked) {
document.getElementById("total-price").value //ADD 42 to value of total-price ;
}
};
我最好的办法是什么?干杯!
答案 0 :(得分:1)
HTML:
<input type="checkbox" id="extra-bathroom" name="extra-bathroom" value= "1" style="display: inline;" onchange="updatePrice();">Extra bathroom?
<input id="total-price" type="button" value= 0 style="width: 100%; margin-top: 5px;">
使用Javascript:
window.updatePrice = function () {
if (document.getElementById('extra-bathroom').checked) {
document.getElementById('total-price').setAttribute("value", parseInt(document.getElementById("total-price").value) + 42);
}
else {
document.getElementById('total-price').setAttribute("value", parseInt(document.getElementById("total-price").value) - 42);
}
};
基本上,你只需获得价值(你所做的事)并设置属性&#34;值&#34;该div的当前值(解析为int,否则它会连接0和42,结果为#34; 042&#34;)+ 42。
我还添加了取消选中复选框的情况。如果未选中,则会将42删除为当前值。
工作小提琴: