Page 1 of 1

Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 5:20 am
by klevis miho
I have this form

Code: Select all

<form name="myform" action="" method="post">
<div id="course1">
Bob<input type="checkbox" name="course[]"  value="bob" />
Charles<input type="checkbox" name="course[]"  value="charles" />
John<input type="checkbox" name="course[]"  value="john" />
<input type="button" name="check_all" value="Check All" onClick="CheckAll(document.getElementsByName('course[]'))" />
</div>
<input type="submit" />
</form>
and this JavaScript function that selects all checkboxes with the name "course[]":

Code: Select all

function CheckAll(chk)
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}
This code works as expected, but my question is:
How can I check all the checkboxes which are inside the div with the id="course1"?

I will have more divs with id="course2", "course3" etc.

Any help would be appreciated.

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 7:53 am
by josh
in jquery
$('div.class checkbox')

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 8:43 am
by klevis miho
How to josh? I don't understand.

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 9:18 am
by josh
First "include" jquery on your page with a <script> tag

http://code.jquery.com/jquery-1.4.1.js

The $ is just an alias to the jquery() function. You can see I just pass it the CSS selector names of the elements I want it to find. The great thing about jquery is the code is so damn simple, and automatically works in modern browsers.

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 9:59 am
by klevis miho
Thnx josh, but I found a function that solved my problem:

Code: Select all

function checkByParent(aId, aChecked) {
    var collection = document.getElementById(aId).getElementsByTagName('INPUT');
    for (var x=0; x<collection.length; x++) {
        if (collection[x].type.toUpperCase()=='CHECKBOX')
            collection[x].checked = aChecked;
    }
}

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 10:09 am
by pickle
I'm not sure getElementsByTagName() exists in all browsers.

Re: Get all checkboxes inside a div

Posted: Fri Jan 29, 2010 10:13 am
by klevis miho
I tried it in chrome, firefox and IE6, and it works