在JavaScript中计算多个输入值

时间:2019-06-16 20:59:10

标签: javascript

我有多个项目,您可以在其中输入数量。我已经编写了该函数,但仅适用于第一项。

我在HTML中使用了相同的className和ID,所以我认为它将在有输入的任何地方加起来。

我把它放在小提琴https://jsfiddle.net/detgz2Ls/

我必须将所有东西都使用相同的类/ ID,因为这将是一个能够动态生成多个项目的列表。

<body>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
  <span>Item 1</span>
</div>
<div>
  <span class="cost">$100.00</span>
</div>
<div id="qty">
  <label>QTY:</label><input placeholder="0" class="qty-item">
  <p class="error"></p>
</div>
<div class="tot">
  <span><label>TOTAL</label> $0.0</span>
</div>
</div>
<br><br>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
   <span>Item 2</span>
</div>
<div>
  <span class="cost">$50.00</span>
</div>
<div class="qty">
  <label>QTY:</label><input placeholder="0" class="qty-item">
  <p class="error"></p>
</div>
<div class="tot">
  <span><label>TOTAL</label> $0.0</span>
</div>
  </div>

<div class="calc-button">
<button id="calc">Calculate Prices</button>
</div>

// JavaScript

const total = document.querySelector(".tot")
 price = document.querySelector(".cost").innerHTML;
 let textval = document.querySelector('.qty-item');
const cal = document.getElementById("calc");
const errorMessage = document.querySelector('.error');

cal.addEventListener('mouseover',function(e){

let xPrice =price.split("$");
let parsePrice = parseFloat(xPrice[1]);
if(textval.value==="" || isNaN(textval.value)){

console.log("error");

}else {
let x = parseFloat(textval.value);
let y =parsePrice;

let z = x * y;

total.innerText = z.toFixed(2);
}
});

1 个答案:

答案 0 :(得分:2)

首先,您需要使用querySelectorAll查找所有元素,而不仅仅是第一个。
然后您必须遍历这些元素的整个集合(for循环)。

const total = document.querySelectorAll(".tot")
const price = document.querySelectorAll(".cost"); // remove .innerHTML here -- elements collection has no .innerHTML, no .value, etc.
let textval = document.querySelectorAll('.qty-item');
const cal = document.getElementById("calc");
const errorMessage = document.querySelectorAll('.error');

cal.addEventListener('mouseover',function(e){
    // loop through all price elements
    for (var i = 0; i < price.length; i++) {
        let xPrice =price[i].innerHTML.split("$"); // use .innerHTML here
        let parsePrice = parseFloat(xPrice[1]);

        if(textval[i].value==="" || isNaN(textval[i].value)){
            setMessage("Please enter a number",'red');          
        } else {
            let x = parseFloat(textval[i].value);
            let y =parsePrice;

            let z = x * y;

            total[i].innerText = z.toFixed(2);
        }
    }
});

https://jsfiddle.net/o92nz1gm/2/