簡體   English   中英

我想在 javascript 中選中復選框時對數字求和

[英]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>

根據修復您已有的代碼:

  1. id 是唯一的,因此請使用checkbox-offers作為 class 和querySelectorAll ,因為您已經有循環
  2. Js 數字中沒有,所以你需要清除它們以獲得能夠進行數學函數的數字
  3. 在您的循環中,您有(e)女巫指示事件,因此使用e.target來定位該event並歸檔並取其value
  4. 使用offersCheckbox[i]你只需addEventListener ,然后你就可以使用e.target
  5. 您需要使用parseFloat(num)將值轉換為數字
  6. 插入值時需要考慮已經添加的值,如果有一個,如果沒有解析為 0,如果有一些解析為數字並添加到它:
  7. 如果您想添加回來,作為結果的千分之一分隔符,那么這里有很多答案,只需搜索它們。

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* 方法返回什么?

如何在 JavaScript 中用逗號打印一個數字作為千位分隔符

event.target 可以使用哪些屬性?

如何將字符串轉換為 JavaScript 中的 integer?

請注意,您需要利用輸入字段的事件處理程序系統,在這種情況下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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM