[英]Javascript edit input value by addition
所以我有這個復選框:
<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到當前值。
工作提琴:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.