【问题标题】:Javascript edit input value by additionJavascript通过添加编辑输入值
【发布时间】:2015-03-09 16:44:18
【问题描述】:

所以我有这个复选框:

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

    }
};

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

【问题讨论】:

    标签: javascript function onchange addition


    【解决方案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);
        }
    };
    

    基本上,您只需获取值(您所做的事情)并将该 div 的属性“值”设置为当前值(解析为 int,否则它将连接 0 和 42,结果为“042 ") + 42.

    我还添加了未选中复选框的情况。如果未选中,则会将 42 移除为当前值。

    工作小提琴:

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

    【讨论】:

    • 非常感谢。唯一的问题是它似乎对数字进行了四舍五入。因此,如果我的原始值是 0.5 而不是 0。我仍然得到 42 而不是 42.5。我怎样才能将其保留到小数点后 2 位?
    • 使用 parseFloat 代替,在这种情况下并使用 toFixed(2) 强制该值具有 2 位小数。简而言之,执行以下操作:document.getElementById('total-price').setAttribute("value", (parseFloat(document.getElementById("total-price").value) + 42).toFixed(2)); 并将相同的逻辑应用于 -42。新小提琴:jsfiddle.net/s95hvsp5/2(以 42.3 为例)
    • 完美!谢谢你,小伙伴!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多