jeudi 4 octobre 2018

A checkbox for selecting all checkboxes generated by CheckBoxFor

I am using CheckBoxFor to create a form of a bunch of checkboxes. I have added a class to these checkboxes but since CheckBoxFor doesn't add the class to the hidden false checkbox, I can't select groups of these generated checkboxes based upon it.

Here's a sample of the checkbox table that gets generated. When I hit the "Select All" checkbox (the top most one), I want all the checkboxes in that column to be selected. I do not want the whole table selected, just the column. enter image description here

Some of the relevant HTML:

<td><input type="checkbox" name="selectAll" value="NBTC" /></td>
<td><input type="checkbox" name="selectAll" value="Contractors" /></td>
<td><input type="checkbox" name="selectAll" value="Coordinators" /></td>
<td><input type="checkbox" name="selectAll" value="NGO" /></td>
<td><input type="checkbox" name="selectAll" value="Public" /></td>

Example of the CheckBoxFor statements I'm using:

@Html.CheckBoxFor(m => m.NBTCGroup.NBTC_FA_Centroid, new {@class = "NBTC"}

This is the JS I was working with, but since the it's selecting based off the class, it doesn't work to select and unselect all as the false checkbox doesn't have the class added to it.

$(document).ready(function () {
    $('input[name="selectAll"]').click(function () {
    var source = $(this);
    var sourceName = $(this).val();
    if (sourceName == 'NBTC') {
        var checkboxes = document.querySelectorAll('input[class="NBTC"]');
    }
    else if (sourceName == 'Contractors') {
        var checkboxes = document.querySelectorAll('input[class="Contractors"]');
    }
    else if (sourceName == 'Coordinators') {
        var checkboxes = document.querySelectorAll('input[class="Coordinators"]');
    }
    else if (sourceName == 'NGO') {
        var checkboxes = document.querySelectorAll('input[class="NGO"]');
    }
    else if (sourceName == 'Public') {
        var checkboxes = document.querySelectorAll('input[class="Public"]');
    }
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i] != source)
            checkboxes[i].checked = source.checked;
        }
    });

Anybody have any ideas on another way to do this?




Aucun commentaire:

Enregistrer un commentaire