user1072337
user1072337

Reputation: 12935

How to check if any of a series of checkboxes are checked in javascript

I have a series of checkboxes that I populate using a foreach loop (php). The code looks like this:

<input type="checkbox" name="artist_group[]" id="{{$fb_data['fbid']}}" class="input-hidden" data-name="{{$fb_data['name']}}" value="{{$fb_data['fbid']}}" style="display:none;"  />
        <label for="{{$fb_data['fbid']}}">
        <img src="https://graph.facebook.com/{{$fb_data['fbid']}}/picture?width=200&height=200" width="140" height="140" alt="{{$fb_data['name']}}"/>
        <article class="artistName">{{$fb_data['name']}}</article>
        </label> 

What I would like to do is check if any of the checkboxes are checked using javascript. However, I can't do this using the "getElementById" because I want each checkbox to have a unique id (so I can pull the data). I have the name of the checkbox group as an array, so I can send all of the checked boxes to my backend. Can I do the following?:

if (document.getElementByName('artist_group').checked) {
            alert("checked");
        }

Thank you for your help.

Upvotes: 0

Views: 65

Answers (3)

dev7
dev7

Reputation: 6369

Since you tagged jQuery in your question as well, you can use jQuery's $.each.

Just select the elements by the class and not id.

$('.input-hidden').each(function() {
  //this will iterate through all checkboxes
   if ($(this).is(':checked')) {//Per @Felix's comment, this.checked is a more native way of doing it, I personally just prefer to use $(this) when I'm in jQuery context, to be consistent. Using this.checked is quicker though.
    //this will apply just to the checked checkboxes
   }
});

You can also get ONLY the selected checkboxes by:

$('input:checked').each(function() {
   //this will only apply to selected checkboxes
});

Hope this helps!

Upvotes: 0

Johannes H.
Johannes H.

Reputation: 6167

As you also used the jQuery tag for your question: IF you're using jQuery anyway (don't just add it only for this task, that's an overkill!):

if ( ! $('input[name="artist_group"]').is(':not(:checked)') ) {
   // all are selected
}

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816354

You have iterate over the checkboxes and test whether any of them is checked or not. Note that the method name is getElementsByName (Elements with s):

var boxes = document.getElementsByName('artist_group[]');
var checked = false;
for (var i = 0, l = boxes.length; i < l; i++) {
    if (boxes[i].checked) {
        checked = true;
        break;
    }
}

If you are not opposed to newer JavaScript methods, you can also use Array#some:

var checked = Array.prototype.some.call(boxes, function(input) {
    return input.checked;
});

With jQuery, it's even simpler:

var checked = $('input[name="artist_group[]"]:checked').length > 0;

Upvotes: 2

Related Questions