'How to do the Multiline Sum in a textbox by using JavaScript

I am trying to sum numbers from 2 text box and the result to a 3rd text box in a PDF Form (Property of text Boxes set to multiline)

Tried the following code but it is not working to add the values and display the results in each row.

var values1 = this.getField("Text6").value.split("\n");
var values2 = this.getField("Text7").value.split("\n");

this.getField("Text8").value = (values1 + values2 );

Unfortunately this is not working.Can someone help me on this?

Expected output below enter image description here



Solution 1:[1]

You're split()ing a string into arrays, you can't add arrays. You'll need to loop through the arrays to add each number.

Also, the array is an array of strings, because you got it from the value of a textarea, which is going to always return a string. You need to parseInt() the string in order to turn it into a number so it will add the numbers rather than concatenate a string.

function getField(id) {
  return document.getElementById(id);
}

var values1 = this.getField("Text6").value.split("\n");
var values2 = this.getField("Text7").value.split("\n");


for(i = 0; i < values1.length; i++) {
  this.getField("txtSums").value += (parseInt(values1[i]) + parseInt(values2[i])) + "\n";
}
<textarea id="Text6">1
2
3</textarea>
<br />
<br />
<textarea id="Text7">4
5
6</textarea>

<br /><br />

sums:<br />
<textarea id="txtSums"></textarea>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1