search

Home  >  Q&A  >  body text

Convert innerhtml to numbers and do calculations

I'm making a simple material calculator but when I sum the values ​​I get 27002700 instead of 5400 So I tried pushing it to an array and using .map and Number, I rewrote it about 10 times. I'm out of ideas.

const heightValue = document.querySelector(".height-value")
const tottalDiv = document.querySelector(".tottal-div")

let heightArr = []
function rangeSlide2(value){
  heightValue.innerHTML = value;
}
heightArr.push(heightValue.innerHTML)
function tottal() {
 let tonum = heightArr.map(Number)
  tottalDiv.innerHTML = tonum + tonum;
}
<input type="range" name="range" id="height-range" min="2000" max="3500" step="100" value="2700" onchange="rangeSlide2(this.value)" onmousemove="rangeSlide2(this.value)">
        <span class="height-value">2700</span>
        
        <div class="button-div">
      <button type="button" class="submit" onclick="tottal()">tottal</button>
    </div>

    <div class="tottal-div">0</div>

P粉425119739P粉425119739316 days ago395

reply all(1)I'll reply

  • P粉637866931

    P粉6378669312024-01-17 10:39:08

    The result of

    map will be an array and when you try to add two arrays with one value it will be converted to string so [2700 ] [2700] Same as '2700' '2700' = '27002700'.

    So, I think what you need is the reduce method to sum all values.

    const heightValue = document.querySelector(".height-value")
    const tottalDiv = document.querySelector(".tottal-div")
    
    let heightArr = []
    function rangeSlide2(value){
      heightValue.innerHTML = value;
    }
    heightArr.push(+heightValue.innerHTML)
    function tottal() {
      let tonum = heightArr.reduce((acc, item) => acc + item)
      tottalDiv.innerHTML = tonum + tonum;
    }
    <input type="range" name="range" id="height-range" min="2000" max="3500" step="100" value="2700" onchange="rangeSlide2(this.value)" onmousemove="rangeSlide2(this.value)">
            <span class="height-value">2700</span>
            
            <div class="button-div">
          <button type="button" class="submit" onclick="tottal()">tottal</button>
        </div>
    
        <div class="tottal-div">0</div>

    reply
    0
  • Cancelreply