简体   繁体   中英

Sum of Fields from User input in javascript

I am new to writing code and learning. I am trying to add number from user inputs in fields. I have used another reply to this site as template with 3 fields. However, I need to add not only a few fields but many fields (more than 30). I am wondering if there is a way to simplify the code with another method. I am trying to avoid to type getelementbyID so many times. Appreciate your help and mentoring.

Html Portion

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Asset-sum</title>
</head>
<body>
<fieldset>
                <h2>Total assets</h2>

                <p class='a'> <label for='A'>A</label>
                    <input type="number" name="A" id="A" oninput="ass()" placeholder="0"> &euro;<br>
 
                <p class='a'> <label for='B'>B</label>
                    <input type="number" name="B" id="B" oninput="ass()" placeholder="0" min="0">&euro;<br>
                </p>
                <p class='a'> <label for='C'>C</label>
                    <input type='number' name='C' id='C' oninput="ass()" min='0' placeholder="0"> &euro;<br>
                </p>             
            </fieldset>
   <h2>Your total assets are: </h2><output type="number" id="asset" name="asset"> &euro;
            <br>
</body>
</html>

Javascript portion

function ass() {
  var x = document.getElementById('A').value || 0; // default value 0 if input is blank
  var y = document.getElementById('B').value || 0; // default value 0 if input is blank
  var z = document.getElementById('C').value || 0; // default value 0 if input is blank
  var asset = document.getElementById('asset');
  var myResult = parseInt(x, 10) + parseInt(y, 10) + parseInt(z, 10); // parse it here 
  asset.value = myResult;

}

You can use document.querySelectorAll('input') to get multiple html elements and store it in a variable. You can call your function and iterates over those elements and access his values. Try this:

<input type="number" name="A" id="A" oninput="f()" placeholder="0"> &euro;<br>
<input type="number" name="B" id="B" oninput="f()" placeholder="0" min="0">&euro;<br>

 let elements = document.querySelectorAll("input"); console.log(elements); f = () => { for (let i = 0; i < elements.length; i++){ console.log(elements[i].value) } }

You could give all of the sum fields a class name, then use document.getElementsByClassName to get all of them:

 function ass() { var inputs = document.getElementsByClassName('calculation-input') var myResult = 0 for (let i = 0; i < inputs.length; i++) { myResult += parseInt(inputs[i].value || 0, 10) } var asset = document.getElementById("asset"); asset.value = myResult; }
 <p class="a"> <label for="A">A</label> <input type="number" class="calculation-input" name="A" id="A" oninput="ass()" placeholder="0" /> &euro;<br /> </p> <p class="a"> <label for="B">B</label> <input type="number" class="calculation-input" name="B" id="B" oninput="ass()" placeholder="0" min="0" />&euro;<br /> </p> <p class="a"> <label for="C">C</label> <input type="number" class="calculation-input" name="C" id="C" oninput="ass()" min="0" placeholder="0" /> &euro;<br /> </p> <h2>Your total assets are: </h2><output type="number" id="asset" name="asset"></output> &euro;

You could do something along these lines without changing your existing code:

let arrayOfInputValues = document.getElementByClassName('a').getElementsByTagName('input');

You'd then have a new array of input values.

And, making the terrible assumption there are numbers in the resulting array, it's reduce to the rescue:

let totalArrayValues = arrayOfInputValues.reduce((acc, curVal) => acc + curVal, 0)

This query will only select the inputs inside the fieldset that are numeric inputs

you can edit the query to be more specific or general adding ids removing the input type it all depends on what you want

 const fields = document.querySelectorAll('fieldset input[type=number]'); const total = document.getElementById('asset'); let count = 0; function ass(){ fields.forEach(elem => count += Number(elem.value)); total.innerHTML = count; count = 0; }
 <fieldset> <h2>Total assets</h2> <p class='a'> <label for='A'>A</label> <input type="number" name="A" id="A" oninput="ass()" placeholder="0" value=0> &euro;<br> </p> <p class='a'> <label for='B'>B</label> <input type="number" name="B" id="B" oninput="ass()" placeholder="0" min="0" value=0> &euro;<br> </p> <p class='a'> <label for='C'>C</label> <input type='number' name='C' id='C' oninput="ass()" min='0' placeholder="0" value=0> &euro;<br> </p> </fieldset> <h2 id="total">Your total assets are: </h2> <output type="number" id="asset" name="asset"> &euro;

the above example was to make it easy for you to read but optimally I would use reduce

to make it more efficient

function ass(){
      total.innerHTML =  total.innerHTML = [...fields].reduce((acc, curr) => acc + Number(curr.value), 0)
}

this is basically the same as the above code snippet but shorter/ cleaner

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