문제

I'm using some code (see below) that stops the search button on my site from working until some text has been entered into the search input field. This works great, however, before any text has been entered I'm still able to hit 'Enter' on the keyboard and it triggers a 'blank' search – is there also a way to disable the 'Enter' key until some text has been entered?

  <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');
      }
    });
  })();

Any help would be much appreciated.

도움이 되었습니까?

해결책

I hope the following can give you some guidance:

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

And remove the disable attribute of your submit button.

Demo

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top