Skip to main content
Participating Frequently
August 3, 2023
Answered

field text color change depending on if its value is greater or less than another field

  • August 3, 2023
  • 1 reply
  • 2676 views

I'm sorry if this is a duplicate post, but I searched everywhere before deciding to post this.

I need an expression that will allow me to change the color of the text in a field depending on if the field's value is greater than or less than/equal to another field.

So, essentially:

If the value of "Field A" is greater than the value of "Field B", then "Field B" text is red.

If the value of "Field A" is less than or equal to the value of "Field B", then "Field B" text remains black.

Thank you in advance for your help.

This topic has been closed for replies.
Correct answer Nesa Nurani

I just realized something I didn't mention yet. I'm not sure if it matters, but the values entered in these fields are currency.


Is it supposed to do something else?

If the value of 'Field A' is greater than the value of 'Field B' text will be red, if you wish for text to be black until both fields have value then try this:

var A = Number(this.getField("Field A").valueAsString);
var B = Number(event.value);
if(A&&B){
 if(A>B)
 event.target.textColor = color.red;
 else
 event.target.textColor = color.black;}
else
event.target.textColor = color.black;

 

1 reply

try67
Community Expert
Community Expert
August 3, 2023

What should be the text color if Field B is empty, and Field A is not?

Thom Parker
Community Expert
Community Expert
August 4, 2023

Let's assume that empty (blank) is 0. 

Add this code to the Calculation script for field B.

event.target.textColor = ((Number(this.getField("Field A").valueAsString)> Number(event.value))?color.red:color.black;

 

This code will not display the text color while a user is typing into Field B. 

 

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Participating Frequently
March 12, 2024

That's because it's failing the first if-condition: if (0) will return false. Use this:

 

var A = this.getField("ATPL_M_Target").valueAsString;
var B = event.value;
if (A && B) {
    A = Number(A);
	B = Number(B);
	if (A > B)
        event.target.textColor = color.red;
    else
		event.target.textColor = ["RGB", 0 / 255, 176 / 255, 80 / 255];
} else event.target.textColor = color.black;

 

I also removed the innermost else statement since it can never happen, because the if-else if you defined cover all possibilities already.

 


That works great!  Thank you so much for your help.