user3706927
user3706927

Reputation: 69

Do sum operation based on numbers inside an input separated by comma

This is just for learning purposes.

I have an input field in a form and I want to sum all the numbers separated by comma which is inside that input and show the result inside another input with id total on change in the input with id first.

For now i have this and it only do the sum of a specific number when a button is pressed.

var numbers = [65, 44, 12, 4];

function getSum(total, num) {
  return total + num;
}

function myFunction(item) {
  document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
<input value='1,3,5,6' id='first'>
<span id="demo"></span>
<button onclick="myFunction()">Try it</button>

Upvotes: 0

Views: 53

Answers (2)

mplungjan
mplungjan

Reputation: 178026

I tried to find a dupe of the original question, which did not have the current script present but did not succeed. Now the code has been posted, all that was missing was the split.

Here I use split, reduce and additionally trigger the input onload to calculate existing values before more are added

$(function() {
  $("#first").on("input",function() {
    let val = this.value.split(",").reduce((a, b) => +a + +b, 0); // convert to number and add
    $("#res").val(val);
  }).trigger("input")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value='1,3,5,6' id='first'> => <input id="res" value="" />

Plain JS:

function sumIt() {
  var fld = document.getElementById("first");
  var val = fld.value.split(",").reduce((a, b) => +a + +b, 0); // convert to number and add
  document.getElementById("res").value = val;
}
window.addEventListener("load", function() {
  document.getElementById("first").addEventListener("input", sumIt);
  sumIt();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value='1,3,5,6' id='first'> => <input id="res" value="" />

Upvotes: 1

ellipsis
ellipsis

Reputation: 12152

Split the value string in an array and with reduce add them

console.log($('#first').val().split(',').reduce((e,i)=>Number(e)+Number(i)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value='1,3,5,6' id='first'>

Upvotes: 0

Related Questions