Skip to content Skip to sidebar Skip to footer

Using Javascript To Manipulate Html Input (checkbox) Elements Via Type Instead Of Name

I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input el

Solution 1:

This should do it:

<script>functioncheckUncheck(form, setTo) {
    var c = document.getElementById(form).getElementsByTagName('input');
    for (var i = 0; i < c.length; i++) {
        if (c[i].type == 'checkbox') {
            c[i].checked = setTo;
        }
    }
}
</script><formid='myForm'><inputtype='checkbox'name='test'value='1'><br><inputtype='checkbox'name='test'value='1'><br><inputtype='checkbox'name='test'value='1'><br><inputtype='checkbox'name='test'value='1'><br><inputtype='checkbox'name='test'value='1'><br><inputtype='button'onclick="checkUncheck('myForm', true);"value='Check'><inputtype='button'onclick="checkUncheck('myForm', false);"value='Uncheck'></form>

Solution 2:

functionfindCheckBoxes(el, check) {
        for(var i=0;el.childNodes[i];i++)
        {
            var child = el.childNodes[i];
            if (child.type=="checkbox")
            {
                child.checked = check;
            }
            if (child.childNodes.length > 0)
                this.findCheckBoxes(child, check);
        }
    }

Solution 3:

iterate through the form.elements collection and check .type == "checkbox".

var button = getSelectAllButtonInFormSomeHow();
/*all formelements have a reference to the form. And the form has an elements-collection.*/var elements = button.form.elements;

for(var i = 0; i < elements.length;i++) {
    var input = elements[i];
    if (input.tagName == "input" && input.type == "checkbox") input.checked = true;
}

Solution 4:

Every input element has an attribute, type, which for checkboxes is "checkbox" so you could try something like this:

for (var i = 0; i < document.myForm.elements.length; i++) {
    if (document.myForm.elements[i].type == "checkbox") {
        document.myForm.elements[i].checked = true;
    }
}

Solution 5:

If jQuery is an option you can do this rather easily.

See the documentation on jQuery selectors. (The last example in the section shows how to do it with radio buttons but just replace that with check boxes.)

Post a Comment for "Using Javascript To Manipulate Html Input (checkbox) Elements Via Type Instead Of Name"