2017-02-28 64 views
2

我敢肯定,这里有很多类似的问题,但我仍然无法找到答案。我想要的是,如果输入[type =“text”]有一个值,则在文档准备好的标签上添加一个类,如果用户将删除该输入值,则删除该类(更好地说,如果输入对模糊没有价值)。jquery如果输入文本有价值,添加类标签,删除它,如果没有值

到目前为止的代码:

<div class="input-wrap">    
       <input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" /> 
      <label class="demo-label" for="textdemo">{L_USERNAME}</label> 
    </div> 


<script type="text/javascript"> 
jQuery(document).ready(function(){ 
    $('.input-wrap .textdemo').val()) { 
      $('label.demo-label').addClass('input-has-value'); 
    } 

}); 
</script> 

回答

3

这应该做的伎俩:

function checkForInput(element) { 
 
    // element is passed to the function^
 
    
 
    const $label = $(element).siblings('label'); 
 

 
    if ($(element).val().length > 0) { 
 
    $label.addClass('input-has-value'); 
 
    } else { 
 
    $label.removeClass('input-has-value'); 
 
    } 
 
} 
 

 
// The lines below are executed on page load 
 
$('input.textdemo').each(function() { 
 
    checkForInput(this); 
 
}); 
 

 
// The lines below (inside) are executed on change & keyup 
 
$('input.textdemo').on('change keyup', function() { 
 
    checkForInput(this); 
 
});
label.input-has-value { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="input-wrap"> 
 
    <input type="text" name="textdemo" id="textdemo" size="20" value="" class="textdemo" /> 
 
    <label class="demo-label" for="textdemo">{L_USERNAME}</label> 
 
</div>

+0

您的代码正在工作,但我想检查输入是否具有准备好的文档的值。我该怎么做? – Jacksonfive

+0

我已更新我的代码以符合您的要求。 :) – dschu

+0

,我应该用$('input.textdemo')替换$(元素)?因为我只想检查该类的输入。 – Jacksonfive

0

您需要检查,如果输入的值为:

$(document).ready(function(){ 
    if($('.input-wrap .textdemo').val() !='') { 
      $('label.demo-label').addClass('input-has-value'); 
    } 
    $('.input-wrap .textdemo').blur(function(){ 
     if($('.input-wrap .textdemo').val() !='') { 
      $('label.demo-label').addClass('input-has-value'); 
     }else{ 
      $('label.demo-label').removeClass('input-has-value'); 
     } 
    } 
}); 
相关问题