skip to Main Content

Disable enter with blank input

Ever encountered a situation wherein you had a form. And 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. Well here’s a code that does just that..

First you need to include JQuery on your page by: inserting this within the

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Here is a Sample Form

<form id="search-form" name="search-form" method="get" action="search.php">
<input type="text" name="uname" id="uname" value="" size='15' maxlength="40">
<input type="password" name="passwd" id="passwd" size='15' maxlength="50">
<input type="submit"name="search-submit" value="Search" />
</form>
<script>
$('#search-form').submit(function(e) {
if (!$('#uname').val()) {
e.preventDefault();
}
if (!$('#passwd').val()) {
e.preventDefault();
}
});
</script>

Please remember.. for this to work, your Form and input fields should have an “id” attribute.

Alphonse

Editorial Staff at ETN Multimedia is led by Alphonse Tan. Page maintained by Alphonse Tan

Back To Top