user4496950
user4496950

Reputation: 105

jQuery: Looping through checkbox and storing in an array?

I have a page with checkboxes on it, and I'm trying to loop through them when a button is clicked, check if any of them are checked, and if none are checked, I want to display an alert. This is what I have, and it isn't working.

$(document).ready(function() { 
    $('input#addnewwebsite').click(function() {
        $('input[type=checkbox]').each(function() {
            var categories = [];
            var $(this) = $(this);    
            if ($(this).is(':checked') == true) {
                categories.push($(this)); // checked, add to array
                break;
            }
            if (categories != null) {
                alert('You must select at least one category.');
                return false;
            }
        });
    });
});

Upvotes: 3

Views: 1077

Answers (2)

Swaprks
Swaprks

Reputation: 1553

var categories = [];
$(document).ready(function() { 
    $('input#addnewwebsite').click(function() {
        $('input[type=checkbox]').each(function() {

            var $this = $(this);    
            if ( $this.is(':checked') == true) {
                categories.push( $this ); // checked, add to array
                break;
            }

            if (categories.length == 0 ) {
                alert('You must select at least one category.');
                return false;
            }
        });
    });
});

In your code the categories array need to be outside the loop as it is being reinitialized for each checkbox iteration. Also instead of checking categories != null you need to check the length of the array and if its ZERO you alert the message. And you have assigned var $(this) = $(this) which makes no sense. Rather it should be var $this = $(this) or the variable name can be anything.

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20626

You can simply use :checked selector with length.

$('input#addnewwebsite').click(function() {
    var categories = $('input:checkbox:checked');
    if(!categories.length){
       alert('You must select at least one category.');  
    }
})

Why doesn't your code work.

  • You are initialising var categories = []; for every checkbox iteration.

Upvotes: 2

Related Questions