Sibi MG
Sibi MG

Reputation: 67

How to use join function to sum 2 fields in JavaScript

Can someone help me to sum the 2 fields and display the results in one box by using JavaScript.

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

for(i = 0; i < values1.length  ; i++)
{
values1[i] =  parseInt(values1[i]) + "\n";
values2[i] =  parseInt(values2[i]) + "\n";


this.getField("Text8").value = (values1[i]+values2[i]).join("") ;
}   

I am getting the following error: TypeError: (values1 + values2).join is not a function

Upvotes: 1

Views: 99

Answers (1)

NetSkylz
NetSkylz

Reputation: 414

You can't join like that, the join method can only be applied on an array.

You can do this:

this.getField("Text8").value = [values1[i], values2[i]].join("");

But a better way:

this.getField("Text8").value = `${values1[i]}${values2[i]}`;

EDIT:

If you want to do a sum, you can simply do this:

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

If you have string instead of a int as values, then you need to cast their values before:

this.getField("Text8").value = parseInt(values1[i]) + parseInt(values2[i]);

Upvotes: 1

Related Questions