0

I've got the following code to that toggles selecting all checkboxes with a certain name.

The code works great in webkit based browsers but doesn't work at all in IE8.

Selecting toggle all, doesn't select anything.

<label class="checkbox">

<input name="product" type="checkbox" id="7553" value="true" title="option1">
option1
</label>

<label class="checkbox">

<input name="product" type="checkbox" id="65693" value="true" title="option2">
option2
</label>

<label class="checkbox">
<input type="checkbox" onClick="toggle(this)"><strong>Select all</strong>
</label>

Here's the JS

<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('product');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>

Can anyone see why the above doesn't work in IE8?

Thanks

C-M
  • 405
  • 1
  • 6
  • 14

1 Answers1

2

Probably because you should never use for..in on arrays (or, in this case, an array-like object).

Try this:

for( var i=0, l=checkboxes.length; i<l; i++) {
    checkboxes[i].checked = source.checked;
}
Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566
  • `for..in` usage is not *all* bad, see this answer: http://stackoverflow.com/a/9329476/973578 – What have you tried Apr 11 '13 at 14:10
  • Excellent yes. using the plain loop fixes this. Seems a common error. I was probably too hasty in my post. – C-M Apr 11 '13 at 14:10
  • I've changed this slightly as I need it to act on the ID instead of the Name. Problem is it doesn't seem to be working now despite me setting the correct id. – C-M Apr 30 '13 at 08:32
  • ClassName works instead though so it's all good. Cheers, guys. – C-M Apr 30 '13 at 08:45