Copy link to clipboard
Copied
I need a javascript for Complex Calculation where Total + SAI + Pell = Need; but if SAI is a negative number, treat as zero. Can anyone please assist me?
Copy link to clipboard
Copied
Hi @jeremy_1903 when looking for scripts to validate or calculate something in Acrobat I found that ChatGPT returns very useful code. Please check the code if it does exactly what you are looking for because it was generated.
For your example this would be:
// Function to safely get a numeric value from a field
function getFieldNumber(fieldName) {
var field = this.getField(fieldName);
return field && field.valueAsString !== "" ? Number(field.valueAsString) : 0;
}
// Get values from form fields
var pell = getFieldNumber("pell");
var sai = Math.max(0, getFieldNumber("sai")); // Ensure SAI is non-negative
var total = getFieldNumber("total");
// Calculate the sum
var need = pell + sai + total;
// Set the calculated value in the "need" field
this.getField("need").value = need;
See a screen capture of it working here:
Copy link to clipboard
Copied
Use this in "Need" field as custom calculation script:
var total = Number(this.getField("Total").valueAsString);
var sai = Number(this.getField("SAI").valueAsString);
var pell = Number(this.getField("Pell").valueAsString);
event.value = total + Math.max(0, sai) + pell;
Copy link to clipboard
Copied
Hi @jeremy_1903 when looking for scripts to validate or calculate something in Acrobat I found that ChatGPT returns very useful code. Please check the code if it does exactly what you are looking for because it was generated.
For your example this would be:
// Function to safely get a numeric value from a field
function getFieldNumber(fieldName) {
var field = this.getField(fieldName);
return field && field.valueAsString !== "" ? Number(field.valueAsString) : 0;
}
// Get values from form fields
var pell = getFieldNumber("pell");
var sai = Math.max(0, getFieldNumber("sai")); // Ensure SAI is non-negative
var total = getFieldNumber("total");
// Calculate the sum
var need = pell + sai + total;
// Set the calculated value in the "need" field
this.getField("need").value = need;
See a screen capture of it working here:
Copy link to clipboard
Copied
I didn't even consider ChatGPT, thats a great idea for the future. Thank you so much for your help!
Copy link to clipboard
Copied
But here you can also see that Nesa’s code is much shorter and probably more efficient. ChatGPT can be used as a starting point but as you can see below it is great to have the assistance of a professional coder.
Copy link to clipboard
Copied
Use this in "Need" field as custom calculation script:
var total = Number(this.getField("Total").valueAsString);
var sai = Number(this.getField("SAI").valueAsString);
var pell = Number(this.getField("Pell").valueAsString);
event.value = total + Math.max(0, sai) + pell;
Copy link to clipboard
Copied
Thanks, Nesa!