Custom Functions in Expressions
Custom functions enable you to perform any calculations in JavaScript code and use calculation results in expressions within survey JSON schemas. This demo shows how to implement, register, and use a custom function in your survey or form. In this example, a custom function counts matrix rows with a specific value. If all three rows are answered "Agree" or "Strongly agree", the survey displays a form field for positive feedback; if all three rows receive a "Disagree" or "Strongly disagree" value, a form field for negative feedback is displayed.
To implement a custom function for use in expressions, follow the steps below:
Declare a JavaScript function.
This function accepts all arguments in one array-like object. You can pass as many arguments as needed when you call the function from an expression.function myFunc(params) { let q1_value = params[0]; let q2_value = params[1]; // ... return someValue; }
Register your function in
FunctionFactory
.
Call a staticregister()
method on theFunctionFactory.Instance
object. This method accepts a function name that you want to use in expressions and the function itself.import { FunctionFactory } from "survey-core"; function myFunc(params) { // ... } FunctionFactory.Instance.register("myFunc", myFunc);
Use your function in expressions.
The following code shows how to use a custom function in thevisibleIf
property.const surveyJson = { "elements": [{ "type": "text", "name": "my-text-box", // ... "visibleIf": "myFunc({question1}, {question2}) > 0" }, { // ... }] };
Ensure that the custom functions you use in your survey are available in the environment where it will be run. If they are unavailable, and you cannot change the environment, consider using calculated values instead. Unlike custom functions, calculated values are embedded in a survey JSON schema and guaranteed to be available without additional JavaScript code.