views:

515

answers:

3

I have a small list of checkboxes (see below), and I noticed I can use an input element with type="reset" and it will uncheck all the boxes. I know using the input would be better than an "onClick" event of the link, because I wouldn't be relying on JavaScript, but for this example I have both.

<a onclick="javascript:document.myList.reset();" href="#">select none</a>  |
<a href="#">select all</a>
<form name="myList">
  <input type="checkbox" name="item1"/>Item 1<br/>
  <input type="checkbox" name="item2"/>Item 2<br/>
  <input type="reset" name="none"/>
  <input type="submit" name="submit"/>
</form>

What is the best way of implementing the "Select all"? I would probably need to write a JavaScript function that loops through all "input" elements of the form "myList" with type="checkbox" and set the value to "0" or something. Also, what is the correct "cross-browser" way of doing this?

I assume there is no HTML form way of doing this like the reset? (I couldn't find one.)

A: 

Correct, there is no HTML way. You'd have to use JavaScript or another language to implement it.

brendan
+9  A: 

Reset will set it to its initial state. That means that if all of your checkboxes were set to checked before and then changed pressing reset would take them back to that state.

I would suggest using jQuery for for making changes to many elements at a time:

$("form[name='myList'] :checkbox").attr("checked", true);

or with pure JavaScript:

for(var i in document.myList.childNodes)
    if(document.myList.childNodes[i].type == "checkbox")
        document.myList.childNodes[i].checked = true;
Adam Peck
+1  A: 

Yeah, you'd use JS.

for(var ix = 0; ix < document.myList.elements.count; ix++)
    if(document.myList.elements[ix].type == 'checkbox')
        document.myList.elements[ix].checked = true;
chaos
I think it's .checked = true;
Luca Matteis
Thanks, This is nice and simple.I shortened it and put it inline (might pull it out at a later date), and tested it in IE and firefox.Final product:<a onclick="for(var i=0; i<myList.length; ix++) if(myList[i].type == 'checkbox') myList[i].checked = true;" href="#">select all</a>
occhiso