views:

67

answers:

2

Hi, my problem is that my variables are not working in javascript. all variables need names without some character at the beginning, this is the stupid thing...Anyways, im trying to make a funtion that makes "select all checkboxes". It is not working so i looked at the page source/info and found out that the variables were not changing.

this is my input:

echo "<input onclick='checkAll(1);' type='checkbox' name='master'/><br/>";

My function:

function checkAll(i)
{
 for(var i=1; i < <?php echo $num; ?>; i++)
 {
  if(document.demo.master[i].checked == true)
  {
   document.demo.message[i].checked = true;
  }
  else
  {
   document.demo.message[i].checked = false;
  }
 }
}

so yes that's it. I can tell you that i also tried without the <i> in: checkAll("i")

Thanks for the help.

EDIT: each checkbox for each messsage has this code:echo "<input style='margin-left:-15px;margin-top:20px;' type='checkbox' name='message' value='$rid' /><br/>";

====READ THIS=============

EDIT: and also, i tryed a code once upon a time and it worked on another computer, but on mine it wasnt working. We had the exact same code...is that normal? what is wrong?

A: 

Why not just:

function checkAll()
{
 for(var i=0; i < <?php echo $num; ?>; i++)
 {
   document.demo.message[i].checked = true;
 }
}

If you want to toggle the current values:

function toggleAll()
{
 for(var i=0; i < <?php echo $num; ?>; i++)
 {
   document.demo.message[i].checked = !document.demo.message[i].checked;
 }
}

However, that doesn't seem very useful in practice (if A is checked and B and C are unchecked, how often do you want A unchecked and B and C checked?). I would just have Select All and Unselect All buttons.

I removed the parameter, changed i to start at 0 (0-indexed), and just had it unconditionally check the box. Before you had it backwards, so it would check it if it were already checked, and vice versa. And you shouldn't need to ever set it false in a checkAll method.

Also, make the Select All a button:

echo "<input onclick='checkAll(1);' type='button' name='master' value='Select All' /><br/>";
Matthew Flaschen
I think his intention was to provide a checkbox that can toggle a group of checkboxes. Probably better named `toggleAll`
Justin Johnson
yes or checkall, and if they are already checked, then uncheck them
linkcool
A: 

For this problem I use the power of prototype js lib

take your checkbox <input style='margin-left:-15px;margin-top:20px;' type='checkbox' name='message' value='$rid' />

add a class

<input class='checkall' style='margin-left:-15px;margin-top:20px;' type='checkbox' name='message' value='$rid' />

then

$$('.checkall').each(function(item){
   item.checked = true;
});

or if you want the checked/unchecked option

$$('.checkall').each(function(item){
  if(item.checked)
    item.checked = false;
  else
    item.checked = true;
 });
Geek Num 88