Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit form only if at least one checkbox is checked using javascript

I have the following form: https://expogr.com/bankexpokenya/advertise.php

I am filling the details of the form and clicking on the submit button. If I have not checked one checkbox, it gives me a message saying "please select any one checkbox" along with the ok button. After clicking the ok button, the form is getting submitted. For form submission, I have used email method so the form data is sent to the particular emailids.

I have tried the following code:

$(document).ready(function(){
    $("form").submit(function(){
        if ($('input:checkbox').filter(':checked').length < 1){
            alert("Please select at least one option from above!");
            break;
            return false;
        }
    });
});

But its not working.

$(document).ready(function(){
    $("form").submit(function(){
        if ($('input:checkbox').filter(':checked').length < 1){
            alert("Please select at least one option from above!");
            break;
            return false;
        }
    });
});
like image 950
chetan Avatar asked Oct 28 '25 02:10

chetan


1 Answers

The issue is with the break statement, remove that and your code will work as expected. Also, you do not need to use .filter() separately as you can specify :checked as part of the selector:

$(document).ready(function(){
  $("form").submit(function(){
    if ($('input:checkbox:checked').length < 1){
      alert("Please select at least one option from above!");
      return false;
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="checkbox"/>First
  <input type="checkbox"/>Second
  <input type="submit" value="Submit"/>
</form>

You can also try with Event​.prevent​Default():

$(document).ready(function(){
  $("form").submit(function(e){
    if ($('input:checkbox:checked').length < 1){
      alert("Please select at least one option from above!");
      e.preventDefault();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="checkbox"/>First
  <input type="checkbox"/>Second
  <input type="submit" value="Submit"/>
</form>
like image 97
Mamun Avatar answered Oct 29 '25 18:10

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!