Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do nothing on empty textbox when enter is pressed

Tags:

jquery

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>
like image 898
input Avatar asked Nov 23 '11 23:11

input


3 Answers

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

like image 159
Scoobler Avatar answered Sep 20 '22 15:09

Scoobler


<input type="text" name="mytext" onkeypress="return event.keyCode!=13">
like image 20
BumbleShrimp Avatar answered Sep 20 '22 15:09

BumbleShrimp


Try:

$("#search").keydown(function(e) {
  if($(this).val() == "" && e.keyCode == 13) {
    e.preventDefault();
  }
})
like image 40
Alex Peattie Avatar answered Sep 17 '22 15:09

Alex Peattie