簡體   English   中英

當輸入字段為空時顯示/隱藏div(jquery,javascript)

[英]show/hide div when input field is empty(jquery, javascript)

我有一個包含內容的div ,默認隱藏,我想在用戶輸入時在#control的輸入字段中顯示它。

<form>
<input name="control" value="" id="control" />
<div class="show_hide">
  //some content here........
</div>
</form>

 // Bind keyup event on the input $('#control').keyup(function() { // If value is not empty if ($(this).val().length == 0) { // Hide the element $('.show_hide').hide(); } else { // Otherwise show it $('.show_hide').show(); } }).keyup(); // Trigger the keyup event, thus running the handler on page load 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form> <input name="control" id="control" /> <div class="show_hide"> //some content here........ </div> </form> 

在keyup上檢查輸入的值,如果length為0表示為空,則隱藏div,否則顯示

#control附加input事件,如下所示:

$('#control').on('input', function(){
   if($.trim(this.value) != "")
      $(this).next('div.show_hide').show();
   else
      $(this).next('div.show_hide').hide();
});

短版本:

$('#control').on('input', function(){
    $(this).next('div.show_hide').toggle($.trim(this.value) != "");
});

要么

$('#control').on('input', function() {
  $(this).next('div.show_hide').toggle(this.value.length > 0);
});

或(在評論中添加@Rayon答案)

$('#control').on('input', function(){
    $(this).next('div.show_hide').toggle(!this.value);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM