tags:

views:

642

answers:

6

I'm really bad at Javascript and I'm struggling to get my head round it.

What I'm trying to do is get something to select all checkboxes. However everything I have found tries to do it by name, I want to do it by ID or class. Select all by name is just inpractical isn't it?

A: 

I always had a tough time with javascript. You might want to investigate the jQuery javascript library. It's greatly enhanced my ability to solve problems using javascript, as well as create more clear and concise code to manipulate and access the DOM.

With jQuery you should be able to easily select all the checkboxes you'd like by ID and then loop through them setting their value to be checked.

Brian
I wanted to avoid it as not everyone wants to include jQuery, but oh well. It's about time everyone used it. Its all working now :)
Ben Shelock
There's no reason to use jQuery for such a tiny task.
J-P
If Ben's having general troubles with JavaScript though, it may be a good idea for him to check it out.
Brian
+5  A: 
var array = document.getElementsByTagName("input");


for(var ii = 0; ii < array.length; ii++)
{

   if(array[ii].type == "checkbox")
   {
      if(array[ii].className == YOUR_CLASS_NAME)
       {
        array[ii].checked = true;

       }


   }
}

by ID:

var checkbox = document.getElementById(YOUR_ID);

if(null != checkbox)
    checkbox.checked = true;
Kevin
+2  A: 

Using JQuery, you can do this very easilly!

$(".ClassName").attr("checked", "true");

or a single ID

$("#ID").attr("checked", "true");

This an excelent article that explains the differences and compare the "old" way versus the JQuery way

Andrea
Shock horror, another "use jquery" answer...
J-P
A: 

JQuery is great when there's a pattern to match. See Check All Checkboxes with JQuery.

Galwegian
A: 

What if you give all of the checkboxes the same name + a number(ie. chkbox1, chkbox2,etc...). Then in your javascript you would create a for loop to go through the number of checkboxes you have, and do getElementByID("chkbox" + num) (where num is your loop variable).

A: 

Pseudo code:

function checkAll(array_with_id_values)
{
    for (var i = 0, ilen = array_with_id_values.length; i < ilen; i++)
    {
        document.getElementById(array_with_id_values[i]).checked = true;
    }
}

Call it with:

checkAll(['my-unique-id', 'my-other-unique-id', 'my-third-unique-id']);

You should ofc not use such verbose variable names and do checks that the argument is an array and that the element you get is a checkbox etc etc.

anddoutoi