简体   繁体   中英

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;
        }
    });
});

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>

You can remove the break statement.see the below mentioned code.

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

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