HTML data-* Attribute
HTML Global attributes give elements meaning and context. Global attributes are common to all HTML elements; they can be used on all elements, including Formidable's input fields, though they may have no effect on some elements.
The data-* attribute consists of two parts:
- The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
- The attribute value can be any string
This tutorial answers a question posed in the Formidable Slack Community #hot-to channel and demonstrates how to use the HTML data-* attribute with Formidable input fields.
Formidable Already Uses data-*
Examine this HTML Formidable generates for a typical text input field:
The <input> element has quite a few attributes. There are the common attributes of type, id, and name. The field's value (another attribute) is empty, but look at the next attribute. You may have to scroll the code horizontally to see it completely. The attribute is data-invmsg="Text is invalid". This is the default data validation message for a text input field. It is a custom data-* attribute added by the Formidable developers.
Adding Your Custom Data Attribute
To add your own custom data-* attribute, you have to modify the HTML Formidable generates from the form's Customize HTML page. Let's look at the code Formidable uses to create the HTML we examined above:
The Slack Community poster asked how to target a specific element to modify its text with a count of characters from another input field. To target the display element, we'll add its field id to a custom data-* attribute. Modify the input shortcode as follows:
After this simple modification, the full Formidable HTML is:
And the rendered HTML is (again, scroll horizontally):
Accessing the Custom Data Attribute with jQuery
The jQuery below ties everything together. It is based on the Slack poster's question and will display the character count of one or more input fields in a custom HTML field.