JQuery: Quoting via checkbox and storing in an array?

I have a page with checkboxes on it and I am trying to skip them, when a button is clicked, it checks if any of them are checked, and if none of them are checked, I want to display an alert. This is what I have and it doesn't work.

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

      

+3


source to share


2 answers


You can just use a :checked

length selector .

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

      



Why is your code not working.

  • You are initializing var categories = [];

    for each iteration of the checkbox.
+3


source


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 must be outside the loop as it is reinitialized for each iteration of the checkbox. Also, instead of checking the categories! = Null, you need to check the length of the array, and if its ZERO, you will notify the message. And you assigned var $ (this) = $ (this) , which doesn't make sense. Rather, it should be var $ this = $ (this) or the variable name can be anything.

0


source







All Articles