Text input fields

A text input field stores a string as its value and a string as its text. Its value is always a valid string, while its text could be any string entered into its editor.

Text input field

A block with the label "text input:" and a text input field set to "default
text".

Text input field with editor open

The same block with the field being
edited.

Text input field on collapsed block

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

Creation

JSON

{
  "type": "example_textinput",
  "message0": "text input: %1",
  "args0": [
    {
      "type": "field_input",
      "name": "FIELDNAME",
      "text": "default text",
      "spellcheck": false
    }
  ]
}

JavaScript

Blockly.Blocks['example_textinput'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("text input:")
        .appendField(new Blockly.FieldTextInput('default text'),
            'FIELDNAME');
  }
};

The text input constructor takes in an optional value and an optional validator. The value should cast to a string. If it is null or undefined, an empty string will be used.

The JSON definition also allows you to set the spellcheck option.

Serialization and XML

JSON

The JSON for a text input field looks like so:

{
  "fields": {
    "FIELDNAME": "text"
  }
}

Where FIELDNAME is a string referencing a text input field, and the value is the value to apply to the field. The value follows the same rules as the constructor value.

XML

The XML for a text input field looks like so:

<field name="FIELDNAME">text</field>

Where the field's name attribute contains a string referencing a text input field, and the inner text is the value to apply to the field. The inner text value follows the same rules as the constructor value.

Customization

Spellcheck

The setSpellcheck function can be used to set whether the field spellchecks its input text or not.

Text input fields with and without spellcheck

An animated GIF showing two blocks with text input fields. The first block has
spellcheck on and misspelled words are underlined with a wavy red line. The
second block has spellcheck off and misspelled words are not
underlined.

Spellchecking is on by default.

This applies to individual fields. If you want to modify all fields change the Blockly.FieldTextInput.prototype.spellcheck_ property.

Creating a text input validator

A text input field's value is a string, so any validators must accept a string and return a string, null, or undefined.

Here is an example of a validator that removes all 'a' characters from the string:

function(newValue) {
  return newValue.replace(/a/g, '');
}

An animated GIF showing a text input field being validated. When the user
types "bbbaaa" and clicks elsewhere, the field is changed to
"bbb".