How to create HTML5-Style input prompts for text fields
This example shows how to use the tooltip (userName) in a PDF text field to create an HTML5-Style input prompt similar to the example below. The behavior is slightly different from what you can create with HTML5 but it’s about as close as I could get and still have a smooth form filling experience.
Enter your name:
When the field is empty, the prompt text appears. When the field has a value, the value is shown. When you click or tab into the field, the prompt disappears and you are free to type. Clear the form to restore the prompts.
The code to create this effect is extremely simple but if you are not familiar with how PDF form fields function, the reason it works takes a bit more explaining. If you’re not interested in how and why this works, you can download a functioning example by clicking the icon to the right. You can either copy one of the fields from the sample file or you can copy the code below and add it to the custom format script of your text field.
Why this works:
I’ll tackle these issues in reverse order.When defining a field in Adobe Acrobat, you have your choice of how to format the value of the field. Just like in Excel, the value of the field and how it appears on the page can be completely different.
When defining a field in Adobe Acrobat, you have your choice of how to format the value of the field. Just like in Excel, the value of the field and how it appears on the page can be completely different.
As you can see in the script above, we are setting the value of the format event object when the value of its target, the current field, is empty. The value of the format event is a string that Acrobat uses to create and “appearance” for the form field and an “appearance” is a chunk of PDF page content that can be used to display the field by viewers that don’t understand what a field is. Appearances are a kind of fallback for less capable PDF viewers. The formatted value never actually gets stored in the PDF and is never used in calculations, it’s just used to generate the appearance.
So… to create an effect similar to HTML5 input prompts, all we need to do is display an appearance based on the prompt when the field is empty and allow Acrobat to create an appearance as normal if the field has a value. To make the prompt as easy as possible to edit, I decided to use the userName property of the field to hold the prompt. This makes sense for a couple of reasons. The userName property is intended to be used as tooltip text whenever the cursor enters a field and can be used by assistive technology to provide a more user-friendly version of the field name. In other words, PDF already has a perfectly reasonable place to store an input prompt, why not use it?