如果为空,则阻止打开引导下拉列表

时间:2017-07-20 19:06:07

标签: javascript jquery twitter-bootstrap

我有自举文本输入组,其中包含实时搜索结果的下拉列表,默认情况下,当您单击文本框时,下拉列表会打开。我喜欢你有下拉不显示,直到有#34; li"标签在那里。我该怎么做呢? 下面是我的搜索栏html。



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<form class="navbar-form" role="search" method="GET" action="/search">
  <div class="input-group">
    <input type="text" class="form-control searchbar" placeholder="Quick search..." name="q" data-toggle="dropdown" autofocus="autofocus" autocomplete="off" onkeyup="checkTextField();">

    <ul class="dropdown-menu search_results" style="width:100%" role="menu">
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
      <li>test</li>
    </ul>

    <div class="input-group-btn">
      <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
    </div>

  </div>
</form>
&#13;
&#13;
&#13;

我在jquery下面尝试但是没有工作

$(document).ready(function(){ 
$myList = $('.search_results') 
if ( $myList.children().length === 0 ) 
{ $('.search_results').hide(); 
} 
});

1 个答案:

答案 0 :(得分:1)

您需要处理输入事件。然后检查孩子&amp;隐藏ul

$('.searchbar').on('click', function (event) {
   if($(".search_results").children().length<=0){
    $(".search_results").hide();
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<form class="navbar-form" role="search" method="GET" action="/search">
  <div class="input-group">
    <input type="text" class="form-control searchbar" placeholder="Quick search..." name="q" data-toggle="dropdown" autofocus="autofocus" autocomplete="off" onkeyup="checkTextField(event);">

    <ul class="dropdown-menu search_results" style="width:100%" role="menu">
    </ul>

    <div class="input-group-btn">
      <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
    </div>

  </div>
</form>