简体   繁体   中英

How to sum all input values in the DOM with a specific data attribute using jquery

I have to sum all inputs in the DOM with the attribute

data-name="sum"

In the inputs are values like 13.99 etc.

And now I have to make a new input field with the amount of all sum fields.

You can use the attribute selector to select the elements and .each() to iterate over them

var sum = 0;
//iterate all inputs wiht the attribute data-name="sum"
$('input[data-name="sum"]').each(function () {
    sum += +this.value || 0; //to handle NaN
});
console.log(sum)
var sum = 0;
$('[data-name="sum"]').each(function(){
    sum += parseFloat($(this).val());
});

demo

I stuck at mapping all into an array and then sum all together

Using map() and reducing it to the sum:

var sum = $('input[data-name="sum"]').map(function () {
    return +this.value
}).get().reduce(function (a, b) {
    return a + b;
});

I am able to display the sum value of 6 DOM elements with a "line_cost" tag name- this is displayed as a sub-total(seen as "ST" methods). Unfortunately, while dynamically calculating the delivery-cost using the sub-total values, I consistently get "undefined" as a value being displayed under the delivery-cost tab while sub-total works perfectly. I thought to believe the problem was occurring due to the DOM not fully loading before the method was called, yet even with the decision if(document.getElementById("sub_total") != null) , I still achieve an 'undefined' value. What could be the problem for this 'undefined' value occurring?

 function calcST(){
  var i;
  var sum = 0; // initialize the sum
  let p = document.getElementsByTagName("line_cost");

  for (i = 0; i < p.length; i++) {
    if (!isNaN(Number(p[i].innerHTML))) {
       sum = Number(sum + Number(p[i].innerHTML)); // p[i].innerHTML gives you the value
    }

  }

  setST(sum, "sub_total");
}


function setST(sum, item_id){
  let i = document.getElementById(item_id);
  i.innerHTML = sum;
  calcDelivCharge();
}


function getST() {
  if(document.getElementById("sub_total") != null){
let i = document.getElementById("sub_total");
let v = i.innerHTML;
return v;

  }
}


function calcDelivCharge(){

  var delCharge;
  var e = getST();

  if(e < 100){
    delcharge = e*0.10
  }else{
    delcharge = 0;
  }

  setDelivCharge("delivery_charge", delCharge);
}

function setDelivCharge(item_id, delCharge){
  let i = document.getElementById(item_id);
  i.innerHTML = delCharge;
  calculateTAX();
}


function getDelivCharge() {
  let i = document.getElementById("delivery_charge");
  let v = i.innerHTML;
  return v;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM