Skip to content

Instantly share code, notes, and snippets.

@cobbman
Last active December 14, 2015 07:59
Show Gist options
  • Save cobbman/5054897 to your computer and use it in GitHub Desktop.
Save cobbman/5054897 to your computer and use it in GitHub Desktop.
When putting a contact form on a page it's cleaner to have the labels be inside the form elements. This bit of jQuery will remove the values when each element is clicked on and bring it back if the user doesn't enter any information in and leaves the box.
<!--
Notice that the values of each input are what you want it to say when it's not focused,
instead of setting these with JavaScript
(I think it's better this way - keeps the content inside the HTML file).
-->
<form id="contact-form" class="contact" action="javascript:alert('success!');">
<fieldset>
<ul>
<li>
<input type="text" name="name" value="Name..." id="name" />
</li>
<li>
<input type="text" name="email" value="Email..." id="email" />
</li>
<li>
<input type="text" name="phone" value="Phone..." id="phone" />
</li>
<li>
<input type="text" name="subject" value="Subject..." id="subject" />
</li>
<li>
<textarea rows="5" cols="20" name="message">Message...</textarea>
</li>
<li>
<input class="button alignleft style-3" type="submit" value="Send" />
</li>
</ul>
</fieldset>
</form>
//jQuery
$(document).ready(function(){
$('form input:text, form textarea').each(function(){
$.data(this, 'default', this.value);
}).focus(function(){
if ($.data(this, 'default') == this.value) {
this.value = '';
}
}).blur(function(){
if (this.value == '') {
this.value = $.data(this, 'default');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment