Wednesday, March 21, 2012

Add Hints & Auto Focus Form Fields (jQuery)

1: $(document).ready(function () {

   2:          //Focus auto-focus fields
   3:          //  add class="auto-focus" to first field
   4:          $('.auto-focus:first').focus();
   5:          //Initialize auto-hint fields
   6:          //  add class="auto-hint" to fields
   7:          //  needs CSS: .auto-hint{color: #AAAAAA;}
   8:          $('INPUT.auto-hint, TEXTAREA.auto-hint').focus(function () {
   9:                 if ($(this).val() == $(this).attr('title')) {
  10:                         $(this).val('');
  11:                         $(this).removeClass('auto-hint');
  12:                 }
  13:          });
  14:          $('INPUT.auto-hint, TEXTAREA.auto-hint').blur(function () {
  15:                 if ($(this).val() == '' && $(this).attr('title') != '') {
  16:                         $(this).val($(this).attr('title'));
  17:                         $(this).addClass('auto-hint');
  18:                 }
  19:          });
  20:          $('INPUT.auto-hint, TEXTAREA.auto-hint').each(function () {
  21:                 if ($(this).attr('title') == '') { return; }
  22:                 if ($(this).val() == '') { $(this).val($(this).attr('title')); }
  23:                 else { $(this).removeClass('auto-hint'); }
  24:          });
  25:  });

No comments: