These forums are now Read Only. If you have an Acrobat question, ask questions and get help from one of our experts.

Forms and Javascript - Questions from a newb to Acrobat and JS

Renthing
Registered: Oct 24 2008
Posts: 38
Answered

Hi all,

Question 1: I'm attempting to total the values of three cells and then add 10 to that value (with the result being displayed in a fourth cell).
I'm running into an issue with the following JS script:

var a = this.getField("#1");
var b = this.getField("#2");
var c = this.getField("#3");
event.value = (a.value + b.value + c.value) +10;

The result is that I get the sum of a, b, and c and then 10. So if a, b, and c are all 1, the result is "110" (1 and then the 10). How do I get this to give the correct result of 13?

Question 2: I'm also trying to build an "if else" script into a form but I'm running into several issues. The goal I want is for the if else script to look at the value of a particular field and then give a result depending on what was in the field. Here's the code I've been trying (simplified):

var a = this.getField("#1")
if (a.value = 1)
{
event.value = 5;
}
else if (a.value = 2)
{
event.value = 4;
}
else
{
event.value = 3;
}

However, some of the issues I run into are:
1. It always displays -5 no matter what value the #1 field has.
2. Sometimes, depending on a tweak to the code, it does something weird where it changes the value of #1 instead of simply looking at #1 to determine.

I'm totally new to Acrobat and JS combined. Can anyone offer any help or suggestions?

-Ren

George_Johnson
Expert
Registered: Jul 6 2008
Posts: 1876
Whenever doing numerical operations, you should explicitly convert any field values to numbers, which you can do using the unary + operator. An empty field will yield a string when accessing a field's value property, and when you then use the "+" operator, it will cause string concatenation instead of the intended numerical addition. So, you can change your code to:

var a = +getField("#1").value;var b = +getField("#2").value;var c = +getField("#3").value;event.value = a + b + c + 10;

or better yet, to prevent creating unneeded global variables, wrap the code in an anonymous function that calls itself:

(function () { var a = +getField("#1").value;var b = +getField("#2").value;var c = +getField("#3").value;event.value = a + b + c + 10; })();

For the second part, you need to test for equality using the "==" or "===" operator. You're using the assignment operator "=".

if (a.value == 1)
George
Renthing
Registered: Oct 24 2008
Posts: 38
Thank you, George, I got both to work!