Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery stop form submit unless checkbox selected

I've got this code, but it doesn't seem to return true. The alert always shows up. Any thoughts (without needing to create a var in which to store that a checkbox has been selected as that just seems a bit hacky).

Thanks.

$("#form").submit(function(e) {
    $('input[type=checkbox]').each(function () {
        if(this.checked){
            return true;
        }
    });
    alert("Please select at least one to upgrade.");
    return false;
});
like image 307
edwardmlyte Avatar asked Jan 25 '11 16:01

edwardmlyte


2 Answers

You don't need to do the loop to determine if a checkbox is checked. The :checked selector filters out all that are not checked. Then you can use $.length to get a count of the checked inputs.

$("#form").submit(function(e) {
    if(!$('input[type=checkbox]:checked').length) {
        alert("Please select at least one to upgrade.");

        //stop the form from submitting
        return false;
    }

    return true;
});

Additionally, using your approach, a small change should make this work

$("#form").submit(function(e) {
    $('input[type=checkbox]').each(function () {
        if($(this).is(':checked')){
            return true;
        }
    });
    alert("Please select at least one to upgrade.");
    return false;
});

I think you may be simply missing the $() around this

like image 76
Josh Avatar answered Nov 04 '22 21:11

Josh


Just to point out, you're using the id reference #form. Did you mean to just refer to all forms, or does the form have the id form?

like image 45
eykanal Avatar answered Nov 04 '22 20:11

eykanal