找不到输入搜索的值

时间:2018-08-17 08:24:48

标签: javascript jquery html

我正在尝试编辑搜索栏,以便用户搜索时会自动在任一侧添加通配符。

以下代码几乎可以解决问题,因为它在任一侧都添加了通配符。不幸的是,它将它们添加到一个空白搜索词中,从而导致“ **”。对于为什么似乎找不到搜索输入的值感到困惑。

编辑:要清楚一点,问题在于,即使用户输入了文本,在网站上searchfield的值又返回为空白。

$('.search-bar').submit(function() {
  var self = this;
  event.preventDefault ? event.preventDefault() : event.returnValue = false;

  var searchfield = $('.search-input');
  searchfield.val("*" + searchfield.val() + "*");

  self.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/search" method="get" class="input-group search-bar" role="search" style="position: relative;">

  <input type="search" name="q" value="" placeholder="Search our store" class="input-group-field search-input" aria-label="Search our store" autocomplete="off" data-old-term="test">
  <span class="input-group-btn">
    <button type="submit" class="btn icon-fallback-text">
      <span class="icon icon-search" aria-hidden="true"></span>
  <span class="fallback-text">Search</span>
  </button>
  </span>
  <ul class="search-results" style="position: absolute; left: 0px; top: 35px; display: none;"></ul>
</form>

1 个答案:

答案 0 :(得分:0)

针对您的这个问题:

  

不幸的是,它会将它们添加到一个空白搜索词中,从而导致“ **”

只需添加检查,如果输入不为空,则仅提交并搜索。

检查以下内容:

$('.search-bar').submit(function() {
  var self = this;
  event.preventDefault ? event.preventDefault() : event.returnValue = false;

  var searchfield = $('.search-input');
  
  if (searchfield.val()) {
    searchfield.val("*" + searchfield.val() + "*");
    self.submit();
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/search" method="get" class="input-group search-bar" role="search" style="position: relative;">

  <input type="search" name="q" value="" placeholder="Search our store" class="input-group-field search-input" aria-label="Search our store" autocomplete="off" data-old-term="test">
  <span class="input-group-btn">
    <button type="submit" class="btn icon-fallback-text">
      <span class="icon icon-search" aria-hidden="true"></span>
  <span class="fallback-text">Search</span>
  </button>
  </span>
  <ul class="search-results" style="position: absolute; left: 0px; top: 35px; display: none;"></ul>
</form>