Uncategorized

Placing a label inside a text input :: a better way

Problem

The most obvious way to position an input label inside a text input is to add descriptive text to the value attribute.

JavaScript removes the label when the user clicks in the field.

<input type=’text’ name=’fname’ value=’first name’ />

This method has a number of shortcomings:

  • The missing label tag is bad for accessibility, and it isn’t a semantic approach.
  • The label gets passed as a value which adds more work when validating the fields.
  • The typography of the label is usually different from the typed text.
  • The label disappears if the user clicks in the field but leaves it blank.

Solution

Using a solid semantic HTML structure, the label can be positioned under an input with no background.

HTML

<form action='#' method='post'>
<fieldset>
<legend>
Please send me more information <br />about the product on this page
</legend>
<ul>
<li>
<label for='type'><span>Type of Business</span></label>
<input type='text' class='select' value='' id='type' >
</li>
<li>
<label for='first_name' ><span>First Name</span></label>
<input name='first_name' id='first_name' type='text' />
</li>
<li>
<label for='last_name' ><span>Last Name</span></label>
<input name='last_name' id='last_name' type='text' />
</li>
<li>
<label for='phone' ><span>Telephone Number</span></label>
<input name='phone' id='phone' type='text' />
</li>
<li>
<label for='email_input' ><span>Email</span></label>
<input name='email' id='email_input' type='text' />
</li>
</ul>
<input class='login_btn'  type='image' alt='submit' src='images/form_submit.jpg' />
</fieldset>
</form>

CSS

footer {
clear:both;
min-height:50px;
line-height:120%;
}
form ul {
margin:0 0 10px 0;
padding:0;
list-style:none;
}
form li {
display:block;
}
.interior_label li {
position:relative;
width:257px;
height:24px;
}
.interior_label li label{
position:absolute;
z-index:10;
top:0;
left:0;
width:237px;
height:24px;
line-height:24px;
padding:0 10px;
background:url('../images/form_text.jpg');
color:#686d71;
font-size:.9em;
}
.interior_label li input{
display:block;
width:237px;
height:24px;
border:0;
padding:0 10px;
position:absolute;
z-index:11;
top:0;
left:0;
background:none;
}

jQuery/JavaScript

The code below hides the label when clicked and shows it again if it is left empty.

$('.interior_label input').focus(function(){
$(this).parent().find('label span').hide();
});
$('.interior_label input').blur(function(){
if($(this).val()==''){
$(this).parent().find('label span').show();
}
});

Leave a Reply

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

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.