Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?

Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.

like image 767
Julien Chastang Avatar asked Jan 20 '09 23:01

Julien Chastang


People also ask

How do I preselect a checkbox in HTML?

You can code a checkbox to be pre-selected when the page loads using the checked boolean attribute. You simply have to add the word checked within the opening tag of the input element.


2 Answers

This should do it:

<script>
function checkUncheck(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>

<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>
like image 92
Paolo Bergantino Avatar answered Oct 27 '22 00:10

Paolo Bergantino


function findCheckBoxes(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);
        }
    }
like image 28
Al W Avatar answered Oct 26 '22 23:10

Al W