Add selection / deselect all to dynamic table form

I have a form that contains buttons for adding and removing rows. My javascript function to validate all checkboxes works for the first line, but as soon as I add more lines to the form, the first line is still the only one that gets validated.

Any advice?

Here is my javascript function:

<code>
//checks all rows
function checkAll() {
var masterCheck = document.getElementById('masterCheck');
var on = false;
if(masterCheck.checked==true) {
    document.getElementById('checkbox').checked=true;
} else {
    document.getElementById('checkbox').checked=false;
}
}
</code>

      

And here is the form: http://crimsonroot.com/files/freelance/new.html

Any help is appreciated!

+3


source to share


3 answers


I found out what happened! @Mohammed your answer really helped. I only encountered one or two syntax errors. To check and uncheck all the checkboxes, I need to add a boolean variable as an input to the function like this:

//checks all rows
function checkAll(bool) {
    var masterCheck = document.getElementById('masterCheck');
    var allcheck = document.getElementsByClassName('checkbox');
    var on = false;
    for (var i = 0; i < allcheck.length; i++) {
        if (masterCheck.checked == true) {
            allcheck[i].checked = true;
        } else {
            allcheck[i].checked = false;
        }
    }

} 

      



For some reason, this was the last piece of the puzzle. Thanks for the help!

+1


source


You should try something like this.



$("#masterCheck").click(function () {
     $('input:checkbox').not(this).prop('checked', this.checked);
 });

      

0


source


Since it document.getElementById()

returns the first element, because id cannot be used more than one. To make it usable, add a class checkbox and try the following code:

//checks all rows
function checkAll() {
    var masterCheck = document.getElementById('masterCheck');
    var allcheck = getElementsByClassName('checkbox');
    var on = false;
    for (var i = 0; i < allcheck.length; i++) {
        if (masterCheck.checked == true) {
            allchecked[i].checked = true;
        } else {
            allchecked[i].checked = false;
        }
    }
}

      

0


source







All Articles