jeudi 11 juin 2020

JavaScript how to combine getElementsByName and getElementsById (select all checkbox)

I have this structure:

<input type=checkbox onclick="toggle(this, 'gr0');">
<input type=checkbox name=id[] id=gr0 value=$id> something1
<input type=checkbox name=id[] id=gr0 value=$id> something1
<input type=checkbox name=id[] id=gr0 value=$id> something1
<input type=checkbox name=id[] id=gr0 value=$id> something1

<input type=checkbox onclick="toggle(this, 'gr1');">
<input type=checkbox name=id[] id=gr1 value=$id> something2
<input type=checkbox name=id[] id=gr1 value=$id> something2
<input type=checkbox name=id[] id=gr1 value=$id> something2
<input type=checkbox name=id[] id=gr1 value=$id> something2

<input type=checkbox onclick="toggle(this, 'gr2');">
<input type=checkbox name=id[] id=gr2 value=$id> something2
<input type=checkbox name=id[] id=gr2 value=$id> something2
<input type=checkbox name=id[] id=gr2 value=$id> something2
<input type=checkbox name=id[] id=gr2 value=$id> something2

and when I check the first row where is the onclick function, then it should select all checkboxes with name id[] and id 'gr0' (and uncheck if I uncheck this "master" checkbox same when I do this with the second/third master checkbox where in onclick function is second value 'gr1' or 'gr2'

I have tried this, but it doesnt work:

<script>
    function toggle(source, id_group) {
        checkboxes = document.getElementsByName('id[]').getElementsById(id_group);
        for(var i=0, n=checkboxes.length;i<n;i++) {
            checkboxes[i].checked = source.checked;
        }
    }
</script>

can you please help me out?




Aucun commentaire:

Enregistrer un commentaire