2 Replies Latest reply on Dec 28, 2017 7:46 PM by stepheng54012748

    Help writing a javascript to only add a positive numbers

    stepheng54012748 Level 1

      If anyone is willing to help I would greatly appreciate it.  I have two fields "l1" and "l2" and "l3" that populate with numbers positive or negative.  "l4" is supposed to add "l1" + "l2" ONLY if "l2" is positive.  If "l2" is negative then this number should not be subtracted from "l1" when these two numbers add together.  "l3" will always be a number that is subtracted in this equation.  I wrote my script below and it works perfectly when "l2" is positive.  When it is negative it subtracts from "l1" which is not what I want.  I have looked at this for hours an cannot figure out how to finish this off.  Any input would be much appreciated.


      var theField = this.getField("l1");

      var theValue = theField.value;

      var theField2 = this.getField("l2");

      var theValue2 = theField2.value;

      var theField3 = this.getField("l3");

      var theValue3 = theField3.value;


      if (((+theValue + +theValue2) - +theValue3) > .001) {

          this.getField("l4").value= (((+theValue +

      +theValue2) - +theValue3));


      else {



        • 1. Re: Help writing a javascript to only add a positive numbers
          Thom Parker Adobe Community Professional

          So you actually have 3 fields, not two, in which the user enters numbers.

          Next, you don't need to sign the variables.

          And when a number is negative it automatically means it will be subtracted in a sum. That's mathematics.


          You need to explain this better, but it seems like you want to add l2 if it is positive and ignore it if it is negative, And l3 will always be negative?


          This code might do what you want. you did not explain the meaning of the if statement. You also didn't explain the rules for l1, what if it is negative?

          Place this code to the calculation script for L4


          var l1Val = this.getField("l1").value;

          var l2Val = this.getField("l2").value;

          var l3Val = this.getField("l3").value;


          if(l2Val > 0)

              event.value = l1Val + l2Val - Math.abs(l3Val);


              event.value = l1Val - Math.abs(l3Val);


          The Math.abs() function removes the sign from l3 and guarentees that the absolute value entered into l3 will always be subtracted.  I don't know if this is what you want, but it seems that way from the explanation.

          • 2. Re: Help writing a javascript to only add a positive numbers
            stepheng54012748 Level 1

            Thanks Thom!


            I'm really new at this and learning how to say things correctly.  You actually understood from my vague description and your suggestion worked.  THANK YOU!