bɪˈɡɪnə bɪˈɡɪnə - 4 years ago 423
Javascript Question

How to prevent submitting search form when search field is empty?

Here the code below disables search button when search box is empty. When input type for search button is set to

submit
then neither submit nor the enter key from keyboard submits empty form but when I change input type to
button
and put the cursor inside input field and press enter button even empty form is posted causing reloading of page. How to prevent submitting search form on pressing enter when search field is empty?

<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>

<script>
$(document).ready(function(){
$('.Button').attr('disabled',true);
$('.search').keyup(function(){
if($(this).val().length !=0)
$('.Button').attr('disabled', false);
else
$('.Button').attr('disabled',true);
})
});
</script>

Answer Source

here is your code with some modification:

JsFiddle Demo

$(document).ready(function(){
	// By default submit is disabled 
	$('.Button').prop('disabled', true);

	$('.search').keyup(function() {

		if($(this).val().length !=0 ) {			
			$('.Button').prop('disabled', false); 
		} else {
			$( ".search").focus();		
		    $('.Button').prop('disabled', true);
		    e.preventDefault();
		}
		
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="search.php" method="post">
	<input type="text" class="search" placeholder="search here"/>
	<input type="submit" class="Button" value="search"/>
</form>

JsFiddle Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download