简体   繁体   中英

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>

Add a event listener for the form submission

$('form').submit(function(e){
    // check logic here
    if ($('.search').val().length < 1)
       e.preventDefault()
});

where e.preventDefault will avoid the form being submitted if no value

otherwise the form will submitted normally

You can try like this

$('form').submit(function(e){
    if ($('.search').val().length<=0)
        return false;
});

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

you should use prop instead of attr if you want to change disabled

$(function() {
  $('.Button').prop('disabled', true);
  $('.search').keyup(function() {
    $('.Button').prop('disabled', !$(this).val());
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM