views:

74

answers:

3

HI,

I have an HTML which has several a list of items with a checkbox (these are placed in a table). Each row in the table has the following coloumn:

<input type='checkbox' name='Events[]' value='1'>
<input type='checkbox' name='Events[]' value='2'>
etc

I would like to have make a link names "select all" that when clicked will select all the items.

I am using the following JS, but it is not working.

    function SelectAll(form)
    {
        for(var i in form.Events.childNodes)
            if(form.Events.childNodes[i].type == "checkbox")
                form.Events.childNodes[i].checked = true;
    }
+2  A: 

That will only work for checkboxes that are directly in the <form> tag, and not nested inside any other tags.

The simplest way to do this is to use jQuery:

$(':checkbox', form).attr('checked', true);
SLaks
Including jQuery for only checking checkboxes? Not so good.
Ahmet Kakıcı
@Ahmet: He can then use it elsewhere and probably make the rest of his code far simpler.
SLaks
+4  A: 

Here you go this should work

<input class="Events" type='checkbox' name='Events[]' value='1'>
<input class="Events" type='checkbox' name='Events[]' value='2'>


function SelectAll(form) {
  for (var i = 0; i < form.elements.length; i ++) {
     if (form.elements[i].type == "checkbox" && form.elements[i].className="Events") {
        form.elements[i].checked = true;
     }
  }
)
John Hartsock
You typed an extra = in the assignment statement ;)
BoltClock
Why add the CSS class?
Tim Down
because im not sure about the name of the element. Never used an array with the selector for form.[ElementName]. For Instance Im not sure what form.Events would actually do. But I know the class will work.
John Hartsock
+5  A: 

The name of your input is Events[], so form.Events wouldn't find it

Because square brackets don't fit in JavaScript o.p property access shortcut, you would have to use the explicit string-based notation to get them:

var inputs= form.elements['Events[]'];

the form.elements collection (and the form collection itself—form['Events[]']—which is a non-standardised shortcut to the same thing but with more chance of name clashes) is a bit old-school and has some disadvantages like returning a single element instead of a list when there's only one element. You'd probably be better off using getElementsByName:

var inputs= form.getElementsByName('Events[]');

either way, follow up with:

for (var i= inputs.length; i-->0;)
    inputs.checked= true;

Never use for...in to iterate an Array or array-like sequence. It doesn't do what you think at all. Stick to the old-school indexed loop.

bobince