Skip to content Skip to sidebar Skip to footer

Javascript Check All Checkboxes With Same Id

I have the following

Solution 1:

As has been pointed out in the comments, IDs must be unique, so you can change them to classes if you like. Then you can use this jQuery:

$('input.check11').click(function(){
  $('input.check21').prop('checked',this.checked)
})

bootply example

Also, remove those inline event handlers.

Solution 2:

As said before, each element on a webpage should have a unique ID.

However, it can still be done using querySelectorAll like so:

functionhandleChange(cb) {
    var allCB = document.querySelectorAll("input[id='check21']");
    for(var i=0; i< allCB.length; i++){
        allCB[i].checked=true;
    }
}

Here is the JSFiddle demo

Solution 3:

The idea behind IDs is that they are unique. It's what allows you to get a single element with the getElementById function, while other getElementsByXXX functions return a list of elements (hence the s in getElements).

When you retrieve the POST data (through PHP or another server language), you will need to check if the variable called like the name attribute is set. If it is, then the checkbox was checked. Having multiple checkboxes with the same name like you did won't work. This other SO answer explains how to use POST data from checkboxes very well.

If you choose to go with name="something[]" notation, when you could check all boxes of the second div with:

var checkboxes = myDiv.getElementsByName("something[]");
for(var i=0; i < checkboxes.length; ++i) {
    checkboxes[i].checked = true;
}

You could also use classes, but I think that would just bloat the code while you already need to use names for forms anyway.

Post a Comment for "Javascript Check All Checkboxes With Same Id"