简体   繁体   English

javascript - 当输入为空时隐藏结果

[英]javascript - hide results when input is empty

I have Live Search JSON Data Using Ajax jQuery, and I would like to call more than one JSON file for the search.我有使用 Ajax jQuery 的实时搜索 JSON 数据,我想调用多个 JSON 文件进行搜索。

At the start of the page, with the input empty, the results are not shown.在页面的开头,输入为空,结果不显示。 However, if you write and delete text again in the input, all results are displayed.但是,如果您在输入中再次写入和删除文本,则会显示所有结果。

I would like to hide all the results again when the input is empty again.当输入再次为空时,我想再次隐藏所有结果。

Thank you in advance.先感谢您。

HTML Input: HTML 输入:

<div class="container" style="width:900px;">
   <div align="center">
    <input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
   </div>
   <ul class="list-group" id="result"></ul>
  </div>

JavaScript: JavaScript:

<script>
$(document).ready(function(){
 $.ajaxSetup({ cache: false });
 $('#search').keyup(function(){
  $('#result').html('');
  $('#state').val('');
  var searchField = $('#search').val();
  var expression = new RegExp(searchField, "i");
  $.getJSON('1.json', function(data) {
   $.each(data.entries, function(key, value){
    if (value.title.search(expression) != -1 || value.author.search(expression) != -1)
    {
     $('#result').append('<li class="list-group-item link-class">'+value.title+'  <span class="text-muted">'+value.author+'</span></li>');
    }
   });   
  });
 });
 
 $('#result').on('click', 'li', function() {
  var click_text = $(this).text().split('|');
  $('#search').val($.trim(click_text[0]));
  $("#result").html('');
 });
});
</script>
$('#search').keypress(function() { 
if($(this).val().length > 1) { 
// Continue work 
} else { 
$('#result').html('') 
}

Using keypress and keydown check the length before the text change.使用keypresskeydown检查文本更改前的长度。 You can use keyup and change .您可以使用keyupchange

It is better to use it with keyup :最好将它与keyup一起使用:

$('#txt1').keyup(function() {
    if (!$(this).val().length) $('#result').html('');
});

You can also use change :您还可以使用change

$('#txt1').change(function() { 
    if (!$(this).val().length) $('#result').html('');
});

The change will be executed when you click somewhere else on the page.当您单击页面上的其他位置时,将执行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM