Advanced JavaScript in Forms ("Fancy Stuff")

Inline Functions

Sometimes, you want a formula or "show if" expression to do really fancy stuff. Perhaps you want to do an "if/then/else" type of expression to decide whether a section of questions resolves to level 1 or level 2. It could be a lot more complicated than that (see the probability of readmission score for an example).

You will find that adding a simple if (x) { return y; } won't work. For example,

if (ScriptUtil.sum(mySection) > 5) return 2; else return 1; 

... won't work. The trick is that you need to define and execute a function inline. Like this:

function() { if (ScriptUtil.sum(mySection) > 5) return 2; else return 1;}() 

Technical details:

To  break this down, this part defines the function:

function() { if (ScriptUtil.sum(mySection) > 5) return 2; else return 1;}

And the "()" at the end simply runs the newly defined function.

Date Manipulations

You can create a new Date in Javascript using the "new Date()" call, which returns the current date/time instant. You can use "new Date(2020,2,10)" to create a date for March 10, 2020 (yes, March; the month is confusingly 0-indexed, so January is month 0).

You can call (new Date().getMonth()) to get the current month (0-indexed again, so March == 2).

To compare dates, simply subtract them to obtain the number of milliseconds in between, then divide that difference by (1000*60*60*24) to get the difference in days.

Google "Javascript date reference" for more information.

Advanced Javascript

As long your script evaluates to a single expression, you can do pretty much anything that you can do with Javascript. Some advanced scripting functionality uses an inline function as described above to have a complicated multi-line algorithm wrapped in a single expression.

You can learn more about Javascript using Google (e.g. "how do I compare dates in Javascript?") or by reading a good reference book (e.g. "Javascript: The Good Parts").


Learn More 

1. Getting Started with eForms 10. Action Menu - eForm Actions
2. Creating a New Form & Understanding Form Structure 11. Adding Hyperlinks to eForms
3. Adding eForm Items - General Tab 12. Editing an Existing Form
4. Editing Menu Choices 13. Helpful eForm Formatting Tips
5. Note Formatting for Items 14. Form Memory - Storing Form Values for Patients in Ocean
6. Using Keywords to Automatically Insert Content 15. Basics of Java Script
7. Adding a Section - Overview 16. Formula Scripting
8. Scripting & More Tab Basics 18. ScriptPatient ("Pt") Functions
9. Action Menu - eForm Properties 19. ScriptUtil Functions


Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request