Search code examples
javascriptjqueryonfocus

Jquery hide label if input contains value


I am using the following code to hide and show a label in my form with Jquerys onBlur and Focus.

Everything works apart from the label showing when there is a value in one of the inputs. (I echo values into my inputs using php when validation fails so users don't have to retype)

How can I get the following code to check if the input has a value and if so hide the label and show it again when value is blank:

CSS

div#first-name,
div#last-name,
div#email-address,
div#password
 {
    position:relative;
    float:left;
    margin-right:3px;
}
label.overlabel {
    color:#999;
}
label.overlabel-apply {
    position:absolute;
    top:3px;
    left:5px;
    z-index:1;
    color:#999;
    padding-left:10px;
    padding-top:10px;
}

Input:

   <div id="first-name">
 <label for="first-name-field" class="overlabel">First name</label>
 <input id="first-name-field" type="text" name="first_name" />
   </div>

Javascript:

$(document).ready(function() {



    // plugin definition
    $.fn.overlabel = function( options ) {

        // build main options before element iteration
        var opts = $.extend( {}, $.fn.overlabel.defaults, options );

        var selection = this.filter( 'label[for]' ).map( function() {

            var label = $( this );
            var id = label.attr( 'for' );
            var field = document.getElementById( id );

            if ( !field ) return;

            // build element specific options
            var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;

            label.addClass( o.label_class );

            var hide_label = function() { label.css( o.hide_css ) };
            var show_label = function() { this.value || label.css( o.show_css ) };

            $( field ).
                 parent().addClass( o.wrapper_class ).end().
                 focus( hide_label ).blur( show_label ).each( show_label );

        //How to hide label if input contains value

            return this;

        } );

        return opts.filter ? selection : selection.end();
    };

    // publicly accessible defaults
    $.fn.overlabel.defaults = {

        label_class:   'overlabel-apply',
        wrapper_class: 'overlabel-wrapper',
        hide_css:      { 'text-indent': '-10000px' },
        show_css:      { 'text-indent': '0px', 'cursor': 'text' },
        filter:        false

    };

$(document).ready(function() {
    $("label.overlabel").overlabel();
});

Solution

  • why not use something like

    if ($(field).val() != ""){
      var fieldId = $(field).attr("id");
      $("label[for='"+fieldId+"']").hide();
    }
    

    typed this without validating syntax.