Reputation: 3171
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.)
Upvotes: 1
Views: 1363
Reputation: 29976
Correct, there is no HTML way. You'd have to use JavaScript or another language to implement it.
Upvotes: 0
Reputation: 7045
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;
Upvotes: 10
Reputation: 124277
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;
Upvotes: 1