2

I got stuck with a simple piece of functionality which seems not to work on different browsers.

My need is to have a single checkbox (master checkbox) with a function to check/uncheck other checkboxes (children checkboxes). When the master checkbox is clicked, it's own state has to be transferred to a list of other checkboxes. For example: If the master checkbox is not checked and gets clicked (and therefore selected), all the child checkboxes should get selected as well.

The code below works excellent in Firefox 13.0.1, but not in Internet Explorer 9.

All the code below is in the same file:

JavaScript

<script type="text/javascript">
    function toggle(source) {   
        checkboxes = document.getElementsByName('cb[]');
        for each(var checkbox in checkboxes)
            checkbox.checked = checkbox.checked == true ? false : true;
    }
</script>

The Checkbox which is clicked for check and uncheck

<td width="3%"><input name="cb_all" type="checkbox" id="cb_all" onClick="toggle(this)"></td>

One single row

<td><input name="cb[]" type="checkbox" value="<?php echo $user->id;?>" id="cb[]"></td>

I like to believe that the solution should be a simple one, but after spending half a day of searching it would be very nice to have some help. Can you please help me with this one?

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • That `for` loop would be a syntax error in every browser. Can you check it and make sure that what you've posted is exactly the same as the actual code you're having a problem with? – Pointy Jul 01 '12 at 13:48
  • Also, simpler way to toggle a boolean value: `checkbox.checked = !checkbox.checked;` – Pointy Jul 01 '12 at 13:49
  • Hello Pointy. I double checked: it is exactly the same –  Jul 01 '12 at 13:51
  • That `for each` syntax is a syntax error; there should be no `each`. – Pointy Jul 01 '12 at 13:53
  • I modified the code to checkbox.checked = !checkbox.checked; and the result is the same. In FF it works but not in IE –  Jul 01 '12 at 13:54
  • Have you used IE9 javascript debugger to see where it is either skipping or not working properly? – James Black Jul 01 '12 at 14:06

1 Answers1

1

It is because Internet Explorer doesn't have a method called getElementsByName . The workaround is to use getElementsByTagName and check each one, you can get more information at http://webbugtrack.blogspot.com/2007/08/bug-411-getelementsbyname-doesnt-work.html

Skatox
  • 4,237
  • 12
  • 42
  • 47
  • MSDN documentation claims that there *is* a `getElementsByName()` in IE. I thought the same as you however. – Pointy Jul 01 '12 at 13:52
  • Thank you Skatox for the link. I'll have a look –  Jul 01 '12 at 13:55
  • I found the answer, or at least one that works for me: –  Jul 01 '12 at 15:27
  • Interesting, so the problem was with the checked attribute. – Skatox Jul 01 '12 at 19:10