当搜索输入字段为空时,停止“输入”键

时间:2014-02-23 01:28:44

标签: jquery search key enter disabled-control

我正在使用一些代码(见下文)阻止我网站上的搜索按钮工作,直到某些文字输入搜索输入字段。这很好,但是,在输入任何文本之前我仍然可以在键盘上点击“Enter”并触发“空白”搜索 - 是否还有一种方法可以禁用“输入”键,直到某些文本为止进入了吗?

  <div class="standard-search-box">
    <form class="search-form" action="/search">
        <label for="q" id="search-label" class="screen-reader-text">Search</label>
        <input aria-labelledby="search-label" id="q" type="search" name="q" class="search-field" placeholder="enter search term…" value autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
        <input type="submit" value="Search" class="search-button" disabled="disabled">
    </form>
  </div>


  (function() {
    $('input.search-field').keyup(function() {

      var empty = false;
      $('input.search-field').each(function() {
        if ($(this).val() == '') {
          empty = true;
        }
      });

      if (empty) {
        $('input[type=submit]').attr('disabled', 'disabled');
      } else {
        $('input[type=submit]').removeAttr('disabled');
      }
    });
  })();

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我希望以下内容可以为您提供一些指导:

 $('#q').bind("keyup keypress", function(e) {
  var code = e.keyCode || e.which; 
  if (code  == 13) {    
      if($(this).val()==''){
          e.preventDefault();
          return false;
      }
  }
});

并删除提交按钮的禁用属性。

Demo