user547794
user547794

Reputation: 14511

How can I ensure at least one checkbox is checked in a particular div?

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?

Upvotes: 2

Views: 2090

Answers (4)

adeneo
adeneo

Reputation: 318212

You can actually just do:

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

FIDDLE1

FIDDLE2

Upvotes: 0

Tats_innit
Tats_innit

Reputation: 34107

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" />​
​

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

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/

Upvotes: 5

jay c.
jay c.

Reputation: 1561

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

Upvotes: 0

Related Questions