jQuery: make HTML5 placeholder attribute work in older browsers
by gabrieleromanato
HTML
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" placeholder="Enter your name" name="name" />
</div>
<div>
<label for="email">E-mail</label>
<input type="text" placeholder="Enter a valid e-mail address" name="email" />
</div>
<p><input type="submit" name="submit" value="Send" /></p>
</form>
CSS
form {
margin: 2em auto;
width: 40em;
}
label {
display: block;
font-weight: bold;
margin-bottom: 0.3em;
}
div {margin-bottom: 1em;}
div input {
background: #fcfcfc;
border: 1px solid #ccc;
width: 15em;
font: 1em sans-serif;
padding: 0.5em;
display: block;
margin-top: 0.4em;
}
div input:focus {background: #f5f5f5; outline-style: none; border: 1px solid #999;}
p {
margin: 1em 0;
}
JavaScript
$('input[placeholder]').each(function() {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
$(this).focus(function() {
if ($(this).val() == $(this).attr('placeholder')) $(this).val('');
});
$(this).blur(function() {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
}
});
}
});
$('form').submit(function(evt) {
$('input[placeholder]').each(function() {
if ($(this).attr('placeholder') == $(this).val()) {
$(this).val('');
}
});
evt.preventDefault();
});