views:

34

answers:

2

Hello!

In my form, my checkbox elements' name are onSite[].

I've made a simple JavaScript to check them with one click.

function checkAll(field)
{
for (i = 0; i < field.length; i++)
    field[i].checked = true ;
}

And in the HTML a button which calls the function.

<input type="button" name="CheckAll" value="All" onClick="checkAll(document.sharepage.onSite[])">

Unfortunately it doesn't work because I'm making array of the checked elements, and the [] confuse my JS.
Do you know any solution to fix it?

+5  A: 

Use square bracket notation when you need to access a property which has a name that includes special characters.

document.forms.sharepage.elements['onSite[]']
David Dorward
A: 

Try separating the onclick handler from HTML.

document.getElementById("bt1").onclick = function(){
  CheckAll();
};

function CheckAll()
{
  var elems = document.forms.sharepage.elements['onSite[]'];
  var len = elems.length;

  for (i = 0; i < len; i++)
  {
    elems[i].checked = true;
  }
}

rahul
Why?...........
Tim Down
Since its a good practice to use unobtrusive javascript.
rahul
Changing to the unobtrusive approach doesn't address the OP's problem and has a major downside in this instance: if you were to, for example, attach this click handler after the document has loaded, which is a common scenario, the user may be able to click on the button before the event handler has been attached and hence not experience the desired behaviour.
Tim Down