Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warn user if all checkboxes are unchecked

I have a form with a series of checkboxes. I want to warn the user, after they hit submit, if ALL of the checkboxes are unchecked. I'm using the following code to report all of the values of the checkboxes:

$('[id^=leg_rider]').filter(':checked');

This seems to work. However, when I try to check to see if the returned object is empty, it doesn't seem to work. This is what I'm trying:

        $("#set_pref_submit").click(function() {
        var legchecked = $('[id^=leg_rider]').filter(':checked');
        if (!legchecked){ alert("no riders")};
    });

Any suggestions are appreciated. Thanks!

like image 208
mb52089 Avatar asked Aug 02 '12 23:08

mb52089


People also ask

How do I check if a checkbox is unchecked?

To check if all checkboxes are unchecked with JavaScript, we can select all the checked checkboxes with document. querySelector . to add a form with some checkboxes. to select all the checked checkboxes with document.

How do you check if all the checkboxes are checked in JavaScript?

type == 'checkbox' && inputs[x]. name == 'us') { is_checked = inputs[x]. checked; if(is_checked) break; } } // is_checked will be boolean 'true' if any are checked at this point.

How do you check all checkbox is checked or not in jquery?

So the correct code is: $('input. abc'). not(':checked'). length === 0 .


2 Answers

You can use jQuery object's length property:

$("#set_pref_submit").click(function() {
    var legchecked = $('input[id^=leg_rider]:checked').length;
    if (legchecked){ alert("no riders")};
});
like image 184
undefined Avatar answered Oct 01 '22 10:10

undefined


Working Demo : http://jsfiddle.net/MrkfW/

Try this: using .change api as well so it keep the track :)

API: http://api.jquery.com/change/

$("input[type='checkbox'][id^=leg_rider]").change(function(){
    var a = $("input[type='checkbox'][id^=leg_rider]");
    if(a.length == a.filter(":checked").length){
        alert('all checked');
    } else {
        alert('not all checked');
    }
});
like image 44
Tats_innit Avatar answered Oct 01 '22 11:10

Tats_innit