Placeholder attribute in HTML5
January 27, 2012 by Manjunath HK · Leave a Comment
I’ve been working on HTML5 extensively now and learning various new stuffs everytime. Today I shall let you know about a new attribute of input element called “placeholder”.
What exactly is placeholder?
Many times you would like to have a textbox have a label within itself. To accomplish this you either use javascript or use jQuery.
But with HTML5 this feature is built-in.
Here is how to implement it:
<input type="text" id="txtUsername" placeholder="Username" />
You can use the placeholder attribute of the input element to show a label within the textbox.
Remember, this feature is supported by all major browsers except Internet Explorer.
How to implement the same for IE?
You can use jQuery to implement the similar functionality that can be supported in IE.
The code would be:
//on document.ready event
$(document).ready(function (){
//for each input with the attribute of placeholder
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
//upon focus of the element
$(this).val(placeholder).focus(function() {
// if the current value is same as placeholder
if($(this).val() == placeholder) {
$(this).val(""); //clear the value.
}
}).blur(function() { //upon blur
if($(this).val() === "") { // if the value is empty
$(this).val(placeholder); //show the placeholder
}
});
});
}
});
I have created a sample page implementing the same here.
I hope you liked this article.
Please provide your feedback in the comments section below.