jQuery - I need a more efficent way to write my forms
//Set default values
$('#name').val('First Last');
$('#email').val('you@email.com');
$('#subject').val('Subject');
$('#message').val('Message');
//Change style when user types
$('#name,#email,#subject,#message').keypress(function() {
$(this).css({
'color':'black',
'font-style':'normal'
});
});
//Check each input for change
$('#name').focusin(function(){
if($(this).val() == 'First Last') {
$(this).val('');
}
});
$('#name').focusout(function() {
if($(this).val() == '') {
$(this).val('First Last');
$(this).css({
'color':'grey',
'font-style':'italic'
});
}
});
$('#email').focusin(function(){
if($(this).val() == 'you@email.com') {
$(this).val('');
}
});
$('#email').focusout(function() {
if($(this).val() == '') {
$(this).val('you@email.com');
$(this).css({
'color':'grey',
'font-style':'开发者_如何转开发italic'
});
}
});
$('#subject').focusin(function(){
if($(this).val() == 'Subject') {
$(this).val('');
}
});
$('#subject').focusout(function() {
if($(this).val() == '') {
$(this).val('Subject');
$(this).css({
'color':'grey',
'font-style':'italic'
});
}
});
$('#message').focusin(function(){
if($(this).val() == 'Message') {
$(this).val('');
}
});
$('#message').focusout(function() {
if($(this).val() == '') {
$(this).val('Message');
$(this).css({
'color':'grey',
'font-style':'italic'
});
}
});
There are a number of plugins out there that handle this style of In-Field Labels.
- In Field Labels -- I wrote this one, and it uses positioning to move the label over (or under via z-index) the input area. It has the added benefit of not disappearing completely even after the field has focus. It only hides fully when the user starts to type.
- Labelify -- Never used it, but it follows your approach of swapping out actual text values.
I recommend the "Jquery Form Plugin" available here: http://jquery.malsup.com/form/#ajaxSubmit
Good luck!
精彩评论