如果在JQUERY中keyup为空,如何显示div

时间:2019-03-26 08:53:01

标签: javascript jquery html

我有一个代码来显示在搜索框中输入的div内容。

$(document).ready(function(){
  $("#myInput").on("keyup", function() { //#myinput is the search box
    var value = $(this).val().toLowerCase();

//#myList is the content that displays the searched data.
    $("#myList .card").filter(function() { 
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

现在我要显示此div

<div class="alert alert-warning text-center" id="emptyList" style="display:none;">
        <strong>No data found!</strong> You can add product by clicking the button "Add item" below or <a href="addItem.php">click here</a>
</div>

如果过滤器为空。

我对jquery还是陌生的,所以你们可以帮我吗?

2 个答案:

答案 0 :(得分:2)

您可以使用:visible伪选择器添加可见卡片的支票,例如:

$(document).ready(function() {
  $("#myInput").on("keyup", function() { //#myinput is the search box
    var value = $(this).val().toLowerCase();

    //#myList is the content that display the searched data.
    $("#myList .card").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });

    if (!$("#myList .card:visible").length) {
      $('#emptyList').show();
    } else {
      $('#emptyList').hide();
    }
  });
});

shorhand版本可以这样写:

$('#emptyList').toggle(!$("#myList .card:visible").length);

答案 1 :(得分:0)

您需要检查输入字段是否为空

    $(document).ready(function(){
      $("#myInput").on("keyup", function() { //#myinput is the search box
        var value = $(this).val().toLowerCase();

        if(value.lenght() =< 0){
          $('div').append('
               <div class="alert alert-warning text-center" id="emptyList"  style="display:none;"><strong>No data found!</strong> You can add product by clicking the button  "Add item" below or <a href="addItem.php">click here</a></div>')
          }
     else{
          //#myList is the content that displays the searched data.
           $("#myList .card").filter(function() { 
             $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
           });
        }   
      });
   });