javascriptjqueryinputhints

Losing input hints after clearing inout fields... any work around?


I have two scripts for clearing my form and using input hints. The input hints are not returning AFTER I execute the clear function.

function clear_form_elements(ele) {

$(ele).find(':input').each(function() {
switch(this.type) {
    case 'password':
    case 'select-multiple':
    case 'select-one':
    case 'text':
    case 'textarea':
        $(this).val('');
        $("  .bx4a").removeAttr("style");
        $("  .bxTXTa").removeAttr("style");
        $("  .bxTXTa2").removeAttr("style");
        $("  .bx4a2").removeAttr("style");
        $("  .bx").removeAttr("style");
        $("  .ts").removeAttr("style");
        $("  .button-toggle-on").removeAttr("style");
        $("  .gnM").removeAttr("style");
        $("  .gnF").removeAttr("style");
        break;
    case 'checkbox':
    case 'radio':
        this.checked = false;
   }
  });

 }






 // jQuery Input Hints plugin
 // Copyright (c) 2009 Rob Volk
 // http://www.robvolk.com

jQuery.fn.inputHints=function() {
// hides the input display text stored in the title on focus
// and sets it on blur if the user hasn't changed it.

// show the display text
$(this).each(function(i) {
    $(this).val($(this).attr('title'))
        .addClass('hint');
});

// hook up the blur & focus
return $(this).focus(function() {
    if ($(this).val() == $(this).attr('title'))
        $(this).val('')
            .removeClass('hint');
}).blur(function() {
    if ($(this).val() == '')
        $(this).val($(this).attr('title'))
            .addClass('hint');
});
};

$(document).ready(function() {$('input[title],textarea[title]').inputHints();});

Solution

  • The strategy for hint text is really simple: set the default value of the input to the hint text that you want, then when it gets focus set the value to ''. Then onblur, if the value is still '', set the value to the default value. e.g.

    <label for="userName">Name:<input name="userName" id="userName"
     value="Your full name&hellip;" class="hint"></label>
    
    <script>
    function hintFocus() {
      if (this.value == this.defaultValue) this.value = '';
    }
    function hintBlur(el) {
      if (this.value == '') this.value = this.defaultValue;
    }
    
    // Add the listeners
    var el = document.getElementById('userName');
    el.onfocus = hintFocus;
    el.onblur = hintBlur;
    </script>
    

    Use a standard reset button for the form and give it a listener so it adds the hint class to input type text and textarea (as appropriate) when the form is reset.