Sweetie Sweetie - 5 months ago 20
Javascript Question

Checking and unchecking checkboxes with dynamic ids and class using jquery

I have a grid that has grouping i.e the grid shows products of group. So, the structure has Group and its childs. Same way I will have some other groups and their childs which I am binding like below.I want to check and uncheck the entire sublist on the click of parent.

CSHTML
@{
if (Model.List.Count() > 0)
{
<table>
<tr>
<input type="checkbox" class="cls@(obj.GroupId)" name="@obj.GroupId" onclick="checkUncheckAll(this.class)" />
<td>Name</td>
</tr>
@foreach (var obj in Model.subList)
{
<tr>
<td>
<input type="checkbox" class="cls@(obj.GroupId)" name="@obj.GroupId" /></td>
</td>
<td>
@obj.Name
</td>
</tr>
</table>
}
}


<input type="button" value="Save" onclick="PickAllCheckedRows();" />


I have been trying to do this like below but no success. Also I want to pick all the checked group and its subitems on click of save button. Any help would be really appreciated.

<script type="text/javascript">
function checkUncheckAll(sender) {
alert(sender);
var chkElements = document.getElementsByClassName('chkItems');
for (var i = 0; i < chkElements.length; i++) {
chkElements[i].checked = sender.checked;
}
}

function PickAllCheckedRows() {
}
</script>

Answer

You're calling your function passing in undefined because you're passing this.class:

onclick="checkUncheckAll(this.class)"

Elements don't have a class property (they do have className), and if they did, you dont' want to pass its class, you want to pass the element itself since you're using it as sender.checked.

Just remove the .class from the call.

If you're trying to do all within a group, then you'll need to use className in the function when getting the other checkboxes to check/uncheck:

function checkUncheckAll(sender) {
    var chkElements = document.getElementsByClassName(sender.className);
    // Note ------------------------------------------------^^^^^^^^^^
    for (var i = 0; i < chkElements.length; i++) {
        if (chkElements[i] !== sender) {             // Not strictly necessary I guess, but...
            chkElements[i].checked = sender.checked;
        }
    }
}

That assumes you'll only ever have a single class on the "all" checkboxes.

Comments