Check Box
The CheckBox component provides a single checkbox for collecting binary (yes/no, true/false, agree/disagree) responses from users.
Basic Usage
const agreementCheckbox = new CheckBox({
id: 'terms_agreement',
text: 'I agree to the terms and conditions',
required: true
});
Parameters
Unique identifier for the checkbox.
The label text for the checkbox.
Whether the checkbox must be checked.
A custom validation function that takes the response as input and returns true if valid, or an error message string if invalid.
Custom styles to apply to the checkbox. Available keys are:
root
innerContainer
checkboxFlexContainer
checkbox
checkboxLabel
errorMessage
Data
Response Format
The CheckBox component returns a boolean value:
true // when checked
false // when unchecked
Validation
The CheckBox component validates that:
- The checkbox is checked when required is true.
- Any custom validation provided in the
customValidation
function passes.
If validation fails, it displays an error message.
Advanced
Methods
The CheckBox component inherits methods from the base Element class and includes some specific methods:
Set the response for the checkbox.
Parameters:
value
(boolean): The checked state of the checkbox
checkboxQuestion.setResponse(true);
Validate the current response against the checkbox’s rules.
Returns:
- An object with
isValid
(boolean) anderrorMessage
(string) properties.
const { isValid, errorMessage } = checkboxQuestion.validate();
Example
Here’s an example of how to create a more customized checkbox:
const newsletterSubscription = new CheckBox({
id: 'newsletter_signup',
text: 'Subscribe to our newsletter',
required: false,
customValidation: (response) => {
// Custom validation logic here
return true; // or return an error message string
},
styles: {
root: {
backgroundColor: '#f0f8ff',
padding: '15px',
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
},
checkboxFlexContainer: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-start',
gap: '10px',
},
checkboxLabel: {
color: '#2c3e50',
fontSize: '1.2em',
fontWeight: 'normal',
},
checkbox: {
width: '20px',
height: '20px',
accentColor: '#3498db'
},
errorMessage: {
color: '#e74c3c',
fontWeight: 'bold',
marginTop: '5px'
}
}
});
This example demonstrates how to use custom styling and validation to create a more tailored checkbox component.