0

I've a html checkbox which select all checkbox after click. But unfortunately it's not working. What's the problem in here ?

javascript Code:

<script language="JavaScript">
function toggle(source) {
 checkboxes = document.getElementsByName('contact_no');
  for(var i=0, n=checkboxes.length;i<n;i++) {
  checkboxes[i].checked = source.checked;
  }
}</script>

Php code:

echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact Name</b></td>";    
echo "<td class='tdhead' valign='top' width='100'><b>Contact 
Number</b>";                
echo '<input type="checkbox" onClick="toggle(this)" /> Toggle 
All<br/>';              
echo "</tr>";


while($row = mysqli_fetch_array($result))
{  
  $gid = $row['gid'];
  $contact_name = $row['contact_name'];  
  $contact_no =  $row['contact_no'];
  echo "<tr>";              
  echo "<td class='tdhead2' valign='top'>$contact_name</td>";
  echo "<td class='tdhead2' ><input type='checkbox' value='$gid' name='contact_no[]'' 
  />&nbsp;&nbsp;$contact_no</td>";                  
  echo "</tr>";
}

echo "</table>";
Alex
  • 71
  • 6

4 Answers4

2

The name on each of your elements is: contact_no[] but in your JS code, you getElementsByName('contact_no') - add [] to the getElementsByName call.

Zack Newsham
  • 2,810
  • 1
  • 23
  • 43
1

for a safety, you should handle event object like code below

<script type="text/javascript">
function toggle(evt) {
 evt = window.event || evt;
 var source = evt.srcElement || evt.currentTarget 

 checkboxes = document.getElementsByName('contact_no');
  for(var i=0, n=checkboxes.length;i<n;i++) {
  checkboxes[i].checked = source.checked;
  }
}
</script>
kyungwook
  • 11
  • 1
0
<script language="JavaScript">
    function toggle(source)
    {
        checkboxes = document.getElementsByName('contact_no');
        for(var i=0, n=checkboxes.length;i<n;i++)
        {
            contact_no[i].checked = source.checked;
        }
    }
</script>
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
joy
  • 1
0

One another solution, you can add Id attribute on the main check box from which you want to perform select all action and make the same as class attribute of other check boxes.

E.g.

$(document).ready(function(){
  $('.selectall').change(function({
    var id = $(this).attr('id');

    if ($(this)is(":checked")) {
      $("." + id).attr('checked','checked');

    } else {
      $("." + id).attr('checked','');
    }
  }))
})

I hope this code helps you

RobG
  • 142,382
  • 31
  • 172
  • 209
joy
  • 1
  • There is no jQuery tag. There is no need for an ID. That is very ordinary jQuery—it should use the *prop* method and set the value to a Boolean. – RobG Sep 26 '13 at 04:48