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>
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
<input type="text" name="mytext" onkeypress="return event.keyCode!=13">
Try:
$("#search").keydown(function(e) {
if($(this).val() == "" && e.keyCode == 13) {
e.preventDefault();
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With