-1
$(document).ready(function()
{
   $('#searchInput').keypress(function() 
   {
      if($(this).val() == '')
      {
        $('#button').attr('disabled', true);
      }
      else
      {
        $('#button').removeAttr('disabled');
      }

   });
});

and i added next to button id "disabled" now i have a problem.When I press space and click search button, no problem, Everything is fine.But after I pressed space key and pressed backspace , i am clicking search button and it shows results.I couldn't resolve the problem.I want to prevention space initial.

  • Your question is mixed up. In the comments below you are asking for something that it is not described in your initial question. Please, provide a proper description of what you are trying to achieve and why you failed to achieve it – Alexander Feb 10 '13 at 13:33
  • dear alexander i don't want to space in my search box.I want to prevention blank results.UP CODES WORKED BUT WİTH MOUSE-CLICK.it doesn't work with keyboard-enter – user1880910 Feb 10 '13 at 13:44

3 Answers3

1

Space is not null you should try $.trim() function , trim will remove all the spaces and give only string without any trailing spaces

 $('#searchInput').keypress(function() 
 {
   if ($.trim($(this).val()) == '')
   {
     $('#button').attr('disabled', true);
   }
   else
   {
     $('#button').removeAttr('disabled');
   }
 });
Maddy
  • 791
  • 1
  • 8
  • 22
0

Bizarrely, you are running up against some odd browser behaviour. In IE and Webkit browsers, backspace does not fire a keypress event, so the handler is never executed.

In Firefox, however, the function is run before the value of the element is changed. So when you type space, the function is run and value is still empty. Therefore the button is disabled. Then you press backspace, and the function is run with value is still a one-character string, with a space in it. So the button is enabled.

You need to use keyup instead, as this is run in all browsers when backspace is pressed and it is run after the value is changed.

$(document).ready(function () {
    $('#searchInput').keyup(function () {
        if (this.value == '') {
            $('#button').prop('disabled', true);
        } else {
            $('#button').prop('disabled', false);
        }
    }).keyup(); 
});

Working example

Changes I have made:

  • changing keypress to keyup
  • this.value rather than $(this).val(): much faster
  • prop('disabled', true) rather than attr('disabled', true): this is the correct function to use and avoids doing the odd removeAttr
  • adding keyup() to the end, so the function is also run when the page is first loaded
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

Just a bit minified and use $.trim to prevent enabling by whitespace:

$('#searchInput').keyup(function () {
       $('#button').prop('disabled', !$.trim(this.value));
}).keyup();

Demo

yckart
  • 32,460
  • 9
  • 122
  • 129