2

I have some checkboxes in an HTML for that are set like this :

<td nowrap width='25%'><label><input type='checkbox' name='chk[]' checked onChange="updateWindow('Label 1', this.checked)">&nbsp;Label 1</label></td>

I also have check all / uncheck all links for those checkboxes :

<td><a href="javascript:checkAll(0);">Unckeck all</a></td>

With this code :

function checkAll(checkValue) {
    checkboxes = document.getElementsByName('chk[]');
    for (var checkbox in checkboxes) {
        checkbox.checked = checkValue;
        activateEvent(checkbox, 'change');
     }
}

The starting problem is that ckecking / unchecking the checkboxes like this do not trigger the onChange event and the associated method. So I trigger it manually calling :

function activateEvent(item, actionShortName) {

    if (document.createEventObject){    // dispatch for IE
        item.fireEvent("on" + actionShortName); 
    }
    else {  // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(actionShortName, true, true); // event type,bubbling,cancelable
        item.dispatchEvent(evt);
    }
}

This works fine with IE8, and some older versions of Firefox. But... on firefox 23, I have a javascript error telling me :

"TypeError: item.dispatchEvent is not a function"

How may I do to make this work for all browsers ?

Oliver
  • 23,072
  • 33
  • 138
  • 230

1 Answers1

1

Your for loop is wrong. checkboxes will be a NodeList, and you cannot for(in) over that (unless you are interested in property names).

Use a regular for (var i = 0; i < checkboxes.length; ++i) checkboxes[i]... loop.

nmaier
  • 32,336
  • 5
  • 63
  • 78