2

I have a <div class="answer" id="yesOptions"> and I need to check that at least 1 checkbox inside this particular is checked. If not, I need to return alert('At least 1 checkbox must be checked from this div!');

How can I do this?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
user547794
  • 14,263
  • 36
  • 103
  • 152

4 Answers4

5

How about

var checkedboxes = $('#yesOptions :checkbox:checked').length;

if (checkedboxes === 0){
    alert('At least 1 checkbox must be checked from this div!');
}

Demo at http://jsfiddle.net/f8UhA/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

Working demo http://jsfiddle.net/gvbX5/

You can use grouping, like sample code below and demo above, hope it helps the cause.

Good links:

What is the proper way to uncheck a checkbox in jQuery 1.7?

JQuery - is at least one checkbox checked

code

$('input').change(function() {
    if ($("[name=group1]:checked").length > 0){

    }else{
        alert('select atleast one checkbox');
    }
});

 if ($("[name=group1]:checked").length == 0)
        alert('select atleast one checkbox');


<input type="checkbox" name="group1" value="1"/>
<input type="checkbox" name="group1" value="2" />
<input type="checkbox" name="group1" value="3" />​
​
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0

$("input[type=checkbox]:checked", $("#yesOptions")).length will give you the count of checkboxes that is checked within that div.

jay c.
  • 1,521
  • 10
  • 9
0

You can actually just do:

if (!$("[type='checkbox']", "#yesOptions").is(':checked'))​ 
    alert('At least 1 checkbox must be checked from this div!');​

FIDDLE1

FIDDLE2

adeneo
  • 312,895
  • 29
  • 395
  • 388