Reputation: 110502
I have the following login form:
div.field {
position: relative;
}
label {
font-size: 14px;
position: absolute;
top: 20px;
left: 3px;
}
<div class="username field">
<label for="username">Enter email</label><br />
<input type="text" class="field" name="email" id="id_email">
</div>
<div class="password field">
<label for="password">Enter password</label><br />
<input type="password" class="field" name="password" id="id_password">
</div>
Currently, if a user clicks anywhere where the label text is, nothing will happen (i.e., because the user is clicking on the label text instead of the text input). I want the label text to be in the text input, however, when a user clicks on the text input field, it should ignore the label text. How would I accomplish this?
Upvotes: 2
Views: 12709
Reputation: 1892
Set your labels' z-index to -1 and make your input fields transparent. That way the labels is rendered "behind" the input fields so that when you click on it, the input field receives the event instead of the label.
div.field {
position: relative;
}
label {
font-size: 14px;
position: absolute;
top: 20px;
left: 3px;
z-index:-1;
}
input {
background: transparent;
}
Upvotes: 1
Reputation: 8393
Using a label for placeholder text is simply not a good idea, as it provides a horrible user experience for someone trying to fill out your form.
That aside here are a couple of things to make note of:
input
tags <label>
tag should be equal to the id
attribute of the related element to bind them together. If you want to provide place holder text perform the text replacement with javascript. For example:
<div>
<label for="email">Enter email</label>
<input type="text" class="defaultText" name="email" id="email" title="Enter email" />
</div>
<div>
<label for="password">Enter password</label>
<input type="text" name="password" id="password" />
</div>
Note, the use of jQuery:
$(function() {
$(".defaultText").focus(function () {
if ($(this).val() == $(this)[0].title) {
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".defaultText").blur(function () {
if ($(this).val() == "") {
$(this).addClass("defaultTextActive");
$(this).val($(this)[0].title);
}
});
$(".defaultText").blur();
})();
example fiddle: http://jsfiddle.net/5yBz5/4/
Upvotes: 1
Reputation: 5723
Method 2:
Use jQuery (optional) to capture click the event on the label, then focus the input element:
$("label").on("click",function(){
$(this).parent().children("input").focus();
});
Upvotes: 1
Reputation: 201866
Add onclick="this.innerHTML=''"
to the label
elements. This is far from a perfect solution, but a solution that has optimal usability would have a different approach (label element before the input element), and the issue would not arise.
Upvotes: 1
Reputation: 5723
You should check out the html5 placeholder attribute instead. It's the recommended way of doing this.
Example:
<input type="text" placeholder="placeholder text"></input>
Upvotes: 6