How to sum of input values in sections with JavaScript?

Sometimes, we want to sum of input values in sections with JavaScript.

In this article, we’ll look at how to sum of input values in sections with JavaScript.

How to sum of input values in sections with JavaScript?

To sum of input values in sections with JavaScript, we can convert the node list of inputs to an array.

Then we can use the array map and reduce methods to add the values together.

For instance, we write:

<form>
  <input type="number" value="2" />
  <input type="number" value="0" />
  <input type="number" value="1" />
  <input type="number" value="3" />
  <input type='submit'>
</form>

to add a form.

Then we select the form and input elements with querySelector and querySelectorAll.

Then we set the form.onsubmit property to the form submit handler.

In it, we call e.preventDefault to stop the default submission behavior.

Then we spread the inputs into an array.

Next, we call map with a callback to get the input value and convert them to numbers.

Finally, we call reduce with a callback to add all the numbers together.

Therefore, sum is 6 according to the console log.

Conclusion

To sum of input values in sections with JavaScript, we can convert the node list of inputs to an array.

Then we can use the array map and reduce methods to add the values together.