July 2, 2010

select all checkbox by one checkbox not working

Question by User123

following is my code, can any one tell me whats going wrong.

<input type="checkbox" name="Chk[]" value="<?php echo($arr['id']); ?>" onClick="Click()" id="CK">// all checkboxex
<input onClick="selectall()" type="checkbox" value="yes" name="c1">// one checkbox
/*function called*/
function selectall()
    {
         if(document.frm.chk.value=="false")
         {
             document.frm.chk.value="true";
             for(var i=0; i<document.frm.elements.length; i++)
               {
                 if((document.frm.elements[i].type)=="checkbox")
                   {
                     document.frm.elements[i].checked = true;
                   }
                }
         }
        else if(document.frm.chk.value=="true")
        {
            document.frm.chk.value="false";
             for(var i=0; i<document.frm.elements.length; i++)
               {
                 if((document.frm.elements[i].type)=="checkbox")
                   {
                     document.frm.elements[i].checked = false;
                   }
                }
        }
    }

Answer by Andy Robinson

I grabbed your code and tweaked it slightly bit rough and ready but seems to work…

    <form name='frm'>
<input type="checkbox" name="chk" value="<?php echo($arr['id']); ?>" onClick="Click()" id="CK">// all checkboxex
<input onClick="selectall()" type="checkbox" value="yes" name="c1">// one checkbox
</form>
/*function called*/
<script>
function selectall()
{
if(!document.frm.chk.checked)
{
    document.frm.chk.value="true";
    for(var i=0; i<document.frm.elements.length; i++)
    {
        if((document.frm.elements[i].type)=="checkbox")
        {
            document.frm.elements[i].checked = true;
        }
    }
}
else if(document.frm.chk.checked)
{
  document.frm.chk.value="false";
    for(var i=0; i<document.frm.elements.length; i++)
    {
        if((document.frm.elements[i].type)=="checkbox")
        {
            document.frm.elements[i].checked = false;
        }
    }
}
}
</script>     

Now when clicking the second checkbox it will check/uncheck the other one. Had to check the checked property rather than value.

Oh and like @Gordon said much easier to use a debugger like Firebug to find out why it’s not working. Assuming your form is called is called frm?

Answer by Starx

use document.form not document.frm

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!