Reputation: 16756
I am trying to write some javascript which will check the checkboxes within a div where the checkbox name matches the given name. Here is what I have, but it isn't doing anything:
function checkbox_control(container_id,element_name,status) {
var children = document.getElementById(container_id).childNodes;
alert(element_name);
for(var b=0; b < children.length; b++) {
if(children[b].name == element_name){
children[b].checked = status;
}
}
}
Upvotes: 1
Views: 154
Reputation: 16756
Typical, you post the question, then you instantly find your own answer no matter how long you had been looking before. Changing childnodes to getElementsByTagName('input'):
function checkbox_control(container_id,element_name,status) {
var children = document.getElementById(container_id).getElementsByTagName('input');
for(var b=0; b < children.length; b++) {
if(children[b].name == element_name){
children[b].checked = status;
}
}
}
Upvotes: 0
Reputation: 7663
This works fine for me (jsFiddle example). Any chance it's your click event handler, using ID instead of name, asking for child nodes when they're really descendant nodes (e.g. <div><ul><li><input type="checkbox"></li></ul></div>
), setting status
to something aside from "checked"
, ""
, true
or false
(which all work at least in Chrome)?
Upvotes: 0
Reputation: 767
Try getElementsByTagName instead of childNodes (it makes recursive search of elements). LIke this:
function checkbox_control(container_id,element_name,status) {
var checkboxes = document.getElementById(container_id).getElementsByTagName('input');
for(var b=0; b < checkboxes.length; b++) {
if(checkboxes[b].name == element_name){
checkboxes[b].checked = status;
}
}
}
Upvotes: 1