Select all Checkboxes in HTML
HI,
I have an HTML which has several a list of items with a checkbox (these are placed in a table). Each row in the table has the following coloumn:
<input type='checkbox' name='Events[]' value='1'>
<input type='checkbox' name='Events[]' value='2'>
etc
I would like to have make a link names "select all" that when clicked will select all the items.
I am using the following JS, but it is not working.
function SelectAll(form)
开发者_如何学C {
for(var i in form.Events.childNodes)
if(form.Events.childNodes[i].type == "checkbox")
form.Events.childNodes[i].checked = true;
}
The name
of your input is Events[]
, so form.Events
wouldn't find it
Because square brackets don't fit in JavaScript o.p
property access shortcut, you would have to use the explicit string-based notation to get them:
var inputs= form.elements['Events[]'];
the form.elements
collection (and the form collection itself—form['Events[]']
—which is a non-standardised shortcut to the same thing but with more chance of name clashes) is a bit old-school and has some disadvantages like returning a single element instead of a list when there's only one element. You'd probably be better off using getElementsByName
:
var inputs= form.getElementsByName('Events[]');
either way, follow up with:
for (var i= inputs.length; i-->0;)
inputs.checked= true;
Never use for...in
to iterate an Array or array-like sequence. It doesn't do what you think at all. Stick to the old-school indexed loop.
Here you go this should work
<input class="Events" type='checkbox' name='Events[]' value='1'>
<input class="Events" type='checkbox' name='Events[]' value='2'>
function SelectAll(form) {
for (var i = 0; i < form.elements.length; i ++) {
if (form.elements[i].type == "checkbox" && form.elements[i].className="Events") {
form.elements[i].checked = true;
}
}
)
That will only work for checkboxes that are directly in the <form>
tag, and not nested inside any other tags.
The simplest way to do this is to use jQuery:
$(':checkbox', form).attr('checked', true);
精彩评论