Posted By

jatkins on 11/18/10


Tagged

input forms label textarea labels


Versions (?)

Add labels to input/textarea elements which disappear when they are given focus (if they are empty)


 / Published in: JavaScript
 

Public domain. Will overwrite any existing classes of the element it is applied to, so use my add/remove CSS classes script if you want to retain current classes.

UPDATED 2/25/2011: get function added. Script would have failed without this, unless you changed all instances of get to document.getElementById. Add styling (e.g. change the font color) of the labels by using the "label" class.

  1. function get(elmnt) {
  2. return document.getElementById(elmnt);
  3. }
  4.  
  5. function addLabel(elmnt, label) {
  6. if(get(elmnt).value.replace(/\s/g, '')=='') {
  7. get(elmnt).className = 'label';
  8. get(elmnt).value = label;
  9. }
  10. get(elmnt).onfocus = function() {
  11. if(this.className=='label') {
  12. this.value = '';
  13. this.className = '';
  14. }
  15. };
  16. get(elmnt).onblur = function() {
  17. if(this.value.replace(/\s/g, '')=='') {
  18. this.className = 'label';
  19. this.value = label;
  20. };
  21. }
  22. }

Report this snippet  

You need to login to post a comment.