I thought I’d share a little technique that I occasionally use when coding forms with a limited amount of space. It’s a simple effect that allows you to contain the form input or textarea title within the form allowing the user to click inside the form input to remove it. You often see this used on search fields
firstly we assign a class of ‘form-field’ as well as adding the attribute ‘defaultVal’ with the text that we want to display in our input field.
The code below simply adjusts the input value attribute depending on if the user click in the field and types text so we have a state of change for ‘focus’ and ‘blur’.
$(document).ready(function(){
$('.form-field').each( function () {
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'#ccc'});
});
$('.form-field').focus(function(){
if ( $(this).val() == $(this).attr('defaultVal') ){
$(this).val('');
$(this).css({color:'#000'});
}
});
$('.form-field').blur(function(){
if ($(this).val() == '' ){
$(this).val($(this).attr('defaultVal'));
$(this).css({color:'#ccc'});
}
});
});
<form method="post" action="">
<input type="text" class="form-field" name="Name" defaultVal="Name" value="" />
<input type="text" class="form-field" name="Phone" defaultVal="Phone Number" value="" />
<input type="text" class="form-field" name="Email" defaultVal="Email address" value="" />
<input type="text" class="form-field" name="Url" defaultVal="Site URL" value="" />
</form>
This entry was posted in CSS, Design, Javascript, Learn, Tutorials, Web Tools, featured, jQuery and tagged CSS, Design, Downloads, forms, Javascript, jQuery, Tutorials. Bookmark the permalink.
Yeah, I’d suggest you use placeholder, and you can mod the script to pull the “placeholder” value for pre-HTML5 browsers. You can detect placeholder support:
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
Appreciated – Was just about to try and find something like this!
I use this by exemple, its really simple:
My main issue with this technique is the use of an attribute that is not actually an attribute.
defaultVal obviously does not validate.
as for HTML5 placeholder… very handy indeed, but I believe my client’s requirement of IE6+ compliant site is to be forgotten !
When you submit form the string into the input field is changed by defaultVal string.
Subscribe to all the Papermashup Tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
Follow us on Twitter and get in-stream messages
6 discussions around jQuery form titles