How to make text fields appear and disappear with javascript in Contact Form 7

I typically use the Contact Form 7 plugin to create forms in WordPress. It easily creates forms using shortcodes to generate the input fields. One of the only limitations is that the shortcodes don’t allow you to add javascript behaviors like onClick, onBlur, etc., nor does it support the relatively new “placeholder” attribute. This becomes a problem when I want to set up a form that displays text in an input field that disappears when a user clicks on it. I do this when I don’t want to use a separate label and instead put that information in the text field itself, like “Name” or “Email” etc.

Outside of Contact Form 7 you can achieve this behavior in a few ways. You can use the “placeholder” attribute along with a script like this to add support for legacy browsers. You can also add onBlur and onFocus actions to each input field. Or you can use a jQuery script to add blur and focus behaviors.

If you stick to using Contact Form 7, there’s a way to alter the plugin code to support this feature, but I don’t like to do that because the changes get erased if you update the plugin, which a client might do. The jQuery method I mentioned above can usually be used with Contact Form 7 to make text appear and disappear. However, I ran into a problem when I tried executing this in a Woo Theme. The form code caused the code for the slider in the theme to break. After spending a lot of time trying to fix it, I found a pretty simple solution. You don’t have to use the shortcodes to get the form to work!

First, I used the shortcode to create the HTML for the input field I needed. I then replaced the shortcode with that HTML and added the javascript onBlur and onFocus actions to it. I tested the form and was surprised to find it worked! Here’s the code I used for the text field:

The only downside I can see is that there’s no way to make the field required if you set it up this way. Otherwise it works!

Tweet about this on TwitterShare on FacebookShare on StumbleUponShare on LinkedInShare on Google+Pin on Pinterest

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>