PDF autofill using javascript nested if statement error

316 Views Asked by At

I have a pdf with two input text boxes. 1.) Item Code and 2.) Item

I am trying to populate "Item" based on "item code" but the nested statements are giving me data for the first else if condition below for all cases. For example, I should get "20% 100 ML" for code 5009113 and "25% 50ML" for code 5009111, and so on. Instead, I am getting "20% 100ML" for any and all values in item code. Please help me with this :)

var v = this.getField("Item Code").valueAsString; 
var RXC = Number(v); 
if (v=="") event.value = ""; 
else if (RXC=5009113) event.value = "20% 100ML"; 
else if (RXC=5009111) event.value = "25% 50ML";
else if (RXC=5009112) event.value = "25% 100ML";
else if (RXC=5009099) event.value = "5% 250ML";
else if (RXC=5009110) event.value = "5% 500ML";
1

There are 1 best solutions below

0
On

The conditions in your else if statements contain expressions such as the following:

RXC=5009113

This is an assignment expression: you are assigning the value 5009113 to the variable RXC. This is considered to be a "truthy" statement and therefore it evaluates to true and therefore no more else if statements are considered.

Instead of this you should use the comparison operator ===. Also take a look at this question regarding the difference between == and === - and why it is better to use === here.

I personally prefer to use white space characters to separate out the parts of an expression:

else if (RXC === 5009113)

It makes it easier (for me) to see what is going on - and easier to spot where I may have used = instead of ===.

But I would recommend re-working the entire section of code to use "if/else" with braces, as follows:

if (v === "") {
  event.value = "";
} else if (RXC === 5009113) {
  event.value = "20% 100ML"; 
} else if (RXC === 5009111) { 
  event.value = "25% 50ML";
} ...

And probably even better would be to use a switch statement, as mentioned in the comments. This is going to be less cluttered than several if/else statements: easier to read, debug, and maintain.