Created
March 27, 2013 14:39
-
-
Save ryankinal/5254686 to your computer and use it in GitHub Desktop.
Form placeholders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* requires jQuery */ | |
$(function() { | |
var submitting = false; | |
$('input').focus(function() { | |
var $this = $(this); | |
if ($this.data('placeholder') && $.trim(this.value) === $this.data('placeholder')) | |
{ | |
if ($this.data('type') === 'password') | |
{ | |
this.type = 'password'; | |
} | |
this.value = ''; | |
$this.removeClass('placeholder'); | |
} | |
}).blur(function() { | |
var $this = $(this); | |
if ($this.data('placeholder') && $.trim(this.value) === '') | |
{ | |
if (this.type === 'password') | |
{ | |
$this.data('type', 'password'); | |
this.type = 'text'; | |
} | |
this.value = $this.data('placeholder'); | |
$this.addClass('placeholder'); | |
} | |
}).each(function() { | |
var $this = $(this); | |
if ($this.data('placeholder') && this.value === '') | |
{ | |
if (this.type === 'password') | |
{ | |
$this.data('type', 'password'); | |
this.type = 'text'; | |
} | |
this.value = $this.data('placeholder'); | |
$this.addClass('placeholder'); | |
} | |
}); | |
/* | |
In order to properly validate, we have to make sure | |
the placeholder text doesn't interfere with validation, | |
so when the submit button is clicked, remove placeholder | |
values. | |
*/ | |
$('form').eq(0).submit(function() { | |
$('.placeholder').each(function() { | |
var $this = $(this); | |
if ($.trim(this.value) === $this.data('placeholder')) | |
{ | |
this.value = ''; | |
} | |
}); | |
// After validation is complete, put placeholder text back | |
setTimeout(function() { | |
$('input').each(function() { | |
var $this = $(this); | |
if ($this.data('placeholder') && this.value === '') | |
{ | |
this.value = $this.data('placeholder'); | |
$this.addClass('placeholder'); | |
} | |
}); | |
}, 200); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment