Skip to content

Instantly share code, notes, and snippets.

@twright
Created September 27, 2012 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twright/3791433 to your computer and use it in GitHub Desktop.
Save twright/3791433 to your computer and use it in GitHub Desktop.
Add a placeholder to a textfield
jQuery(document).ready(function() {
// Select the field we want to add the behaviour to
var field = jQuery('#respond input[type="text"][name="ecf_4"]');
// What text do we want to
var placeholder_text = 'your placeholder';
var text_changed = false;
if ('placeholder' in field[0])
/* Modern browsers natively support text field placeholders */
field.attr('placeholder', placeholder_text);
else {
/* For older browsers we can fake it using JavaScript event handlers */
// Set the initial text to the placeholder
field.val(placeholder_text);
// Keep track of whether the user has changed the text of the field
field.change(function() {
if (!(text_changed || $(this).val() === ''))
text_changed = true;
else if (text_changed && $(this).val() === '')
text_changed = false;
});
// Clear the text on focus if it has not been changed by the user
field.focus(function() {
if (!text_changed)
jQuery(this).val('');
});
// Put the placeholder back if the user has not changed the text
field.blur(function() {
if (!text_changed)
jQuery(this).val(placeholder_text);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment