Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top