Introducing an additional input
element with a placeholder can lead to complications during validation and submission of the form
. I found a different solution to this issue.
The HTML
<form id="test">
<input type="text" id="name" name="name" placeholder="Name" />
<input type="password" id="password" name="password" placeholder="Password" />
</form>
jQuery Function
function placeHolder(form) {
form.wrapInner('<ul style="list-style: none; list-style-type:none; padding:0; margin: 0;">');
form.find('input[placeholder]').each(function (index, current) {
$(current).css('padding', 0).wrap('<li style="position: relative; list-style: none; list-style-type:none; padding:0; margin: 0;">');
var height = $(current).parent('li').height();
var $current = $(current),
$placeholder = $('<div class="placeholder">'+$current.attr('placeholder')+'</div>');
$placeholder.css({'color': '#AAA', 'position':'absolute', 'top': 0, 'left': 0, 'line-height': height+'px', 'margin': '0 0 0 5px', 'border': '0 none', 'outline': '0 none', 'padding': 0});
$placeholder.insertAfter($current);
$current.removeAttr('placeholder');
$placeholder.click(function(){
$current.focus()
});
$current.keypress(function(){
if($(this).val().length >= 0) {
$placeholder.hide();
}
});
$current.blur(function(){
if($(this).val().length == 0) {
$placeholder.show();
} else {
$placeholder.hide();
}
});
});
}
Simply invoke the function for your form.
placeHolder($("#test"));
This method applies to all types of input fields with placeholders, including type="password"
, and has been tested in various browsers such as IE8, IE9, IE10, Google Chrome, FireFox, Safari, and Opera.