[英]I want to sum numbers when a checkbox is checked in javascript
我想對數字求和並在跨度中打印出來,我嘗試使用 innerHTML 但因為它是一個我不能的字符串,所以我嘗試了 parseInt、parseFloat、Number 和什么都沒有。 對於所有選中的復選框,我希望將其值的總和放入跨度中,而那些未選中的復選框我不希望它們在跨度中得到總和
(我減少了表格和很多數字,因為放在這里太長了,所以想象一下我想總結很多總數)
const offersCheckbox = document.querySelectorAll("#checkbox-offers"); const recalculateText = document.querySelector(".recalculate-text"); const checkboxTotal = document.querySelectorAll("#checkbox-total"); let total = 0; for (let i = 0; i < offersCheckbox.length; i++) { offersCheckbox[i].addEventListener("click", (e) => { if (offersCheckbox[i].checked === true) { recalculateText.innerHTML = "recalculate invoice total"; } else { recalculateText.innerHTML = ""; } }); }
<table> <tr> <tr> <td> <input type="checkbox" name="checkbox" id="checkbox-offers" value="2,434.38" /> <td> <div class="price-container text-bold" id="checkbox-total"> <b>$</b>2,434.38 </div> </td> </tr> <tr> <td> <input type="checkbox" name="checkbox" id="checkbox-offers" value="76.69" /> </td> <td> <div class="price-container text-bold" id="checkbox-total"> <b>$</b>76.69 </div> </td> </tr> </table> <span class="recalculate-text text-right text-underline"></span>
根據修復您已有的代碼:
checkbox-offers
作為 class 和querySelectorAll
,因為您已經有循環,
所以你需要清除它們以獲得能夠進行數學函數的數字(e)
女巫指示事件,因此使用e.target
來定位該event
並歸檔並取其value
。offersCheckbox[i]
你只需addEventListener
,然后你就可以使用e.target
parseFloat(num)
將值轉換為數字recalculateText.innerHTML = (parseFloat(recalculateText.innerHTML || 0) + num2)
const offersCheckbox = document.querySelectorAll(".checkbox-offers"); const recalculateText = document.querySelector(".recalculate-text"); let total = 0; for (let i = 0; i < offersCheckbox.length; i++) { offersCheckbox[i].addEventListener("click", (e) => { let num = e.target.value.split(",").join("") let num2 = parseFloat(num) if (e.target.checked === true) { recalculateText.innerHTML = (parseFloat(recalculateText.innerHTML || 0) + num2) } else { recalculateText.innerHTML = ""; } }); }
<table> <tr> <tr> <td> <input type="checkbox" class="checkbox-offers" name="checkbox" value="2,434.38" /> <td> <div class="price-container text-bold" id="checkbox-total"> <b>$</b>2,434.38 </div> </td> </tr> <tr> <td> <input type="checkbox" class="checkbox-offers" name="checkbox" value="76.69" /> </td> <td> <div class="price-container text-bold" id="checkbox-total"> <b>$</b>76.69 </div> </td> </tr> </table> <span class="recalculate-text text-right text-underline"></span>
有用的鏈接:
querySelectorAll 和 getElementsBy* 方法返回什么?
請注意,您需要利用輸入字段的事件處理程序系統,在這種情況下onchange
每個輸入字段處理修改每個價格總和的存儲值。
我確實通過正則表達式將貨幣寫入數字規范器,但是我沒有將數字寫入貨幣格式化程序,以將總和重新格式化回貨幣。 你需要自己處理。
let sum = 0; let addPrice = (elem) => { let value = parseFloat(elem.value.replace(/\$|,/g, ''), 2); elem.checked? (sum += value): (sum -= value); document.getElementById('result').innerHTML = sum; };
<table> <tr> <tr> <td> <input type="checkbox" name="price" value="2,434.38" onchange="addPrice(this)" /> <td> <div class="price-container text-bold"> <b>$</b>2,434.38 </div> </td> </tr> <tr> <td> <input type="checkbox" name="price" value="76.69" onchange="addPrice(this)" /> </td> <td> <div class="price-container text-bold"> <b>$</b>76.69 </div> </td> </tr> </table> <div class="recalculate-text text-right text-underline">Total: <span id="result">0</span></div>
我沒有從你的原始代碼中改變太多。 查看評論以了解我所做的更改,如果您有其他問題,請隨時發表評論。
const recalculateText = document.querySelector(".recalculate-text"); const checkboxContainer = document.querySelector("#checkbox-container"); let total = 0; // Create a number formatter to print out on the UI - this is a better approach than regex IMO. const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); //Notice the use of event delegation here - meaning I only added 1 single event handler to a single DOM element //Read this blog for more on event delegation and why it's useful: https://davidwalsh.name/event-delegate checkboxContainer.addEventListener('change', e => { //Also notice that I am listening for the change event, instead of the click event. //See here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event if (e.target.tagName == "INPUT") { const floatValue = parseFloat(e.target.value); if (e.target.checked) { total += floatValue; } else { total -= floatValue; } } recalculateText.innerHTML = formatter.format(total); });
<.-- Notice I added a parent div to enable use to use event delegation technique --> <,-- Also notice I removed element id attributes where they were not needed. Also be sure to always use unique id values for every element - duplicate ids are not allowed. it will lead to bugs. If elements need to be considered part of the same "group" then you should use the class attribute, --> <div id="checkbox-container"> <table> <tr> <tr> <td> <.-- Notice I removed the comma from the value attribute --> <input type="checkbox" name="checkbox" value="2434.38" /> <td> <div class="price-container text-bold"> <b>$</b>2.434.38 </div> </td> </tr> <tr> <td> <input type="checkbox" name="checkbox" value="76.69" /> </td> <td> <div class="price-container text-bold"> <b>$</b>76.69 </div> </td> </tr> </table> </div> <span class="recalculate-text text-right text-underline"></span>
$('input[type="checkbox"]').change(function() {
var checkArray = [];
var total = 0;
$("input:checkbox[name=checkbox]:checked").each(function(key){
checkArray.push($(this).val());
});
if(checkArray.length !== 0) {
total = checkArray.reduce(function(a, b){
return parseInt(a) + parseInt(b);
}, );
$(".recalculate-text").text(total);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.