input
input

Reputation: 7519

Do nothing on empty textbox when enter is pressed

I have a form in which I have a textbox and a button. When the textbox is empty, and the user clicks the button or presses the enter key, it should do nothing. It should not show any error either. What's the best way to do this? I don't want to disable the enter key altogether.

<form id="search-form" name="search-form" method="get" action="search.php">

                    <input type="text" id="search" name="search"/>
                    <input type="submit"name="search-submit" value="Search" />
</form>

Upvotes: 6

Views: 11003

Answers (4)

Aginjith GJ
Aginjith GJ

Reputation: 73

On ASP.NET 2012 onkeydown="return event.keyCode!=13" was working right.

Upvotes: 1

BumbleShrimp
BumbleShrimp

Reputation: 2200

<input type="text" name="mytext" onkeypress="return event.keyCode!=13">

Upvotes: 9

Alex Peattie
Alex Peattie

Reputation: 27647

Try:

$("#search").keydown(function(e) {
  if($(this).val() == "" && e.keyCode == 13) {
    e.preventDefault();
  }
})

Upvotes: 3

Scoobler
Scoobler

Reputation: 9719

Try this, use jQuery's .submit() to capture when the form is being submitted (clicking the button or pressing enter will be captured with the .submit() function), then test the search input is empty (an empty string will return false) and use the .preventDefault() function to stop the form being submitted.

$('#search-form').submit(function(e) {
   if (!$('#search').val()) {
       e.preventDefault();
   }       
});

Demo Here

Upvotes: 11

Related Questions