Reputation: 7519
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
Reputation: 73
On ASP.NET 2012
onkeydown="return event.keyCode!=13"
was working right.
Upvotes: 1
Reputation: 2200
<input type="text" name="mytext" onkeypress="return event.keyCode!=13">
Upvotes: 9
Reputation: 27647
Try:
$("#search").keydown(function(e) {
if($(this).val() == "" && e.keyCode == 13) {
e.preventDefault();
}
})
Upvotes: 3
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();
}
});
Upvotes: 11