Javascript通过加法编辑输入值

Javascript edit input value by addition

本文关键字:编辑 输入 Javascript      更新时间:2023-09-26

所以我有这个复选框:

<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 ;
    }
};

我最好的方法是什么?干杯!

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);
    }
};
基本上,你

只是得到值(你做的事情)并将该div的属性"value"设置为当前值(解析为int,否则它会连接0和42,结果是"042")+ 42。

我还添加了未选中复选框的情况。如果未选中,它将删除当前值的 42。

工作小提琴:

http://jsfiddle.net/s95hvsp5/1/