How to disable a component unless a condition is met?
The enabled state of a component can be changed based on the values of other components by giving the component a Logic object. This Logic
object has a trigger
property where you can specify when the state must be changed, and an actions
property where you specify what must be changed.
In the example below we create a checkbox and a number component for input fields, and a button that is enabled when the checkbox is ticked and the number exceeds five. To get this behaviour we use the disableWhen
function that all components have. Refer to createDisableLogic for more information on the shared inputs.
cb = component.Checkbox("TheCheckbox", form)
cb.label = "I agree"
nr = component.Number("TheNumber", form)
nr.label = "Years of experience"
btn = component.Button("TheButton", form)
btn.label = "Continue"
btn.block = True
btn.disabled = True
# Add enable Logic.
btn.disable_when("javascript", "result = data.TheCheckbox && data.TheNumber > 5", False)
cb = component.Checkbox("TheCheckbox", form);
cb.label = "I agree";
nr = component.Number("TheNumber", form);
nr.label = "Years of experience";
btn = component.Button("TheButton", form);
btn.label = "Continue";
btn.block = true;
btn.disabled = true;
% Add enable Logic.
btn.disableWhen("javascript", "result = data.TheCheckbox && data.TheNumber > 5", false)
The resulting form in action:
Note that only for Buttons the same can be achieved by using the customConditional
property, similar to how this property can be used to hide components.
btn.customConditional = "component.disabled = data.TheCheckbox && data.TheNumber > 5";
Buttons also have the disableOnInvalid
property (default false). When set to true, this disables the button when any value in the form does not meet its component's validation criteria.