Skip to main content

Checkbox fields

A checkbox field stores a string as its value, and a string as its text. Its value is either 'TRUE' or 'FALSE', and its text is either 'true' or 'false'.

Checkbox field

A block with the label "checkbox:" and a checkbox field with a check
mark.

Checkbox field on collapsed block

The same block after being collapsed. It has the label "variable: true" and a
jagged right edge to show it is
collapsed.

Creation

{
"type": "example_checkbox",
"message0": "checkbox: %1",
"args0": [
{
"type": "field_checkbox",
"name": "FIELDNAME",
"checked": true
}
]
}

The checkbox constructor takes in an optional value and an optional validator. The optional value should be either 'TRUE', 'FALSE', or a boolean, otherwise it will default to false.

Serialization

The JSON for a checkbox field looks like so:

{
"fields": {
"FIELDNAME": true
}
}

Where FIELDNAME is a string referencing a checkbox field, and the value is the value to apply to the field. The value must be a boolean.

Customization

Checkmark character

The Blockly.FieldCheckbox.CHECK_CHAR property can be used to change what the checkmark looks like. The value should be a string containing a unicode character.

Checkbox field with heart instead of check

The CHECK_CHAR property defaults to \u2713 or ✓.

This is a global property, so it will modify all checkbox fields when set.

Creating a checkbox validator

note

For information on validators in general see Validators.

A checkbox field's value is either 'TRUE' or 'FALSE' so a validator should accept those values (i.e. a string) and return 'TRUE', 'FALSE', null, or undefined.

warning

the getValueBoolean method should not be used inside of validators, because it returns based on the current value, not the new value.

Here's an example of a validator that hides or shows a text input field based on whether the checkbox is checked:

  validate: function(newValue) {
var sourceBlock = this.getSourceBlock();
sourceBlock.showTextField_ = newValue == 'TRUE';
sourceBlock.updateTextField();

return newValue;
},

updateTextField: function() {
var input = this.getInput('DUMMY');
if (this.showTextField_ && !this.getField('TEXT')) {
input.appendField(new Blockly.FieldTextInput(), 'TEXT');
} else if (!this.showTextField_ && this.getField('TEXT')) {
input.removeField('TEXT');
}
}

Checkbox field with a validator

An animated GIF that shows a checkbox being checked. When the checkbox is
checked, a text field is
displayed.