If you haven’t got a lot of room in your HTML form to put a label above or next to a text input field – you can put the label inside the input field instead!, this can be done in using Javascript or HTML 5 Form Attributes
Using Javascript Attributes; onblur and onfocus
Using a couple of dynamic Javascript attributes ‘onblur‘ and ‘onfocus, this changes the text dynamically based on the focus of the cursor in the text input fields from a default value to a newly entered value.
See the form below:
Tab through the fields and see the text disappear when the focus is on that field and then the original text re-appear if no text has been added in the field. The form has one field that has to be filled in correctly which is the email field.
To set up the form like this you need to add a couple of extra Javascript attributes in each required <input> field.
So for example in the first field the ‘first name’ field the input tag code would be this:
<input id="firstname" class="" name="firstname" type="text" value="First Name" onfocus="if (this.value == 'First Name') {this.value = '';}" onblur="if (this.value == '') " />
The key tags being ‘onfocus‘ and ‘onblur‘.
The code will also work without the regular HTML attribute ‘value‘ tag but this will mean that the initial load of the page will not display the default value, so to include a loaded default value include that value attribute in the code.
Using HTML 5 Form Attributes; placeholder and required
Here the input field requires 2 HTML 5 form attributes, required and placeholder=”placeholder text”. The required attribute tells the browser a value is required and the placeholder does the same job as the onblur/onfocus attributes – just add the placeholder text in between the double quotes
The value attribute is not required as it will clash with the placeholder attribute.
So the equivalent input code for the first name field would be…
<input id="firstname" class="" name="firstname" type="text" placeholder="First Name" required />
If you click Download on the 2nd form without filling in values the browser will display a warning
You can also style the default input placeholder text by following this guide.
The HTML5 solution will work on modern browsers but only on IE10+, to get around earlier IE versions there is a fantastic polyfill javascript solution. I have also created a plugin for its use in WordPress