如果输入包含值,则Jquery隐藏标签

hai*_*ets 1 javascript jquery onfocus

我使用以下代码隐藏和显示我的表单中的标签与Jquerys onBlur和Focus.

除了其中一个输入中有值的标签外,所有内容都有效.(当验证失败时,我使用php将值回显到我的输入中,因此用户无需重新输入)

如何获取以下代码以检查输入是否具有值,如果是,则隐藏标签并在值为空时再次显示:

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;
}
Run Code Online (Sandbox Code Playgroud)

输入:

   <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>
Run Code Online (Sandbox Code Playgroud)

使用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();
});
Run Code Online (Sandbox Code Playgroud)

AyK*_*rsi 7

为什么不使用像

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

键入此而不验证语法.