math.sum how to pass a collection of values as argument?

587 Views Asked by At

i started to use math.js just for convenience and i was wondering if i could use math.sum method and pass a collection of input values as argument and return the sum of all input values,for example,something like this :

code to visualize my concept :

$(document).ready ( function(){
   $("#sum").val(math.sum($("#container input")))
});
input{
position:relative;
float:left;
clear:both;
text-align:center;
}
#sum{
margin-top:5px;
}
<!DOCTYPE html>
<html>
<head>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="container"><input value="15"><input value="5"><input value="10"><input value="20"></div>
<input id="sum" placeholder="SUM OF ABOVE INPUTS">
</body>
</html>

2

There are 2 best solutions below

0
denik1981 On BEST ANSWER

Your math.sum method expects a JS Array so you need to build it from what you have to comply with the requirement.

In just one line you can go from Jquery Objects to your expected Array.

[Jquery DOM Elements].get() => [ES6 DOM Elements].map() => JS Arrays

$("#sum").val(math.sum($("#container input").get().map(v=>v.value)))
input {
  position: relative;
  float: left;
  clear: both;
  text-align: center;
}

#sum {
  margin-top: 5px;
}
<!DOCTYPE html>
<html>
<head>
  <script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>
  <div id="container"><input value="15"><input value="5"><input value="10"><input value="20"></div>
  <input id="sum" placeholder="SUM OF ABOVE INPUTS">
</body>

</html>

0
charlietfl On

You need to map the element values to an array first.

The math library doesn't know anything about getting values from a jQuery collection of elements

Simple case with no validation:

const values = $("#container input").toArray().map(el => el.value)
$("#sum").val(math.sum(values))
input {
  position: relative;
  float: left;
  clear: both;
  text-align: center;
}

#sum {
  margin-top: 5px;
}
<!DOCTYPE html>
<html>

<head>
  <script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>

<body>
  <div id="container"><input value="15"><input value="5"><input value="10"><input value="20"></div>
  <input id="sum" placeholder="SUM OF ABOVE INPUTS">
</body>

</html>