0

So I have a table inside of my view and I have gotten to the point where my select-all checkbox is selecting/unselecting. However I can't seem to get it to select all the checkboxes. It only selects the first checkbox in the list.

enter image description here

Here is a snippet from my view.

<table class="table table-bordered">
<tr>
    <th>@Html.CheckBox("CheckAll", false, new { id = "select_all" })</th>

@for (int i = 0; i < Model.additionalCustomerInfoListView.Count; i++)
{
    <tr>                            
        <td>@Html.CheckBoxFor(model => model.additionalCustomerInfoListView[i].IsSelected, new { id = "someDivId" })</td>

and here is my jQuery

$('#select_all').click(function () {
    var c = this.checked;
    $('#someDivId').prop('checked', c)
});     

Appreciate any help I can get!

snapper
  • 210
  • 3
  • 14
  • 2
    IDs are unique, you cannot have same ID (`someDivId`) multiple times. You should change them to class. – Milan Chheda Jul 27 '17 at 13:19
  • Possible duplicate of [Can multiple different HTML elements have the same ID if they're different elements?](https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme) – mjwills Jul 27 '17 at 13:19
  • 1
    you can take class attribute and apply prop function on it – Vishvadeep singh Jul 27 '17 at 13:20
  • You may try a different selector. Eg.: `$('.table td [type="checkbox"]').prop('checked', c)` – Werner Jul 27 '17 at 13:21
  • You should also consider scripts to uncheck the 'Select All' if previously selected and the user un-checks one row. And also to check it if the user manually un-checks all rows. –  Jul 27 '17 at 23:09

2 Answers2

5

Change new { id = "someDivId" } to new { @class= "someClass"}.

Then Select all elements with "someClass" by using:

$('#select_all').click(function () {
    $('.someClass').prop('checked', this.checked)
});  
TheJoeIaut
  • 1,522
  • 2
  • 26
  • 59
0

You should consider the other way also like when a child checkbox deselected then the parent should also be deselected.

Means if there are 10 checkboxes in table and if one is not selected then you should deselect the parent also.

Here is the code to select parent when you are selecting child checkboxes one by one

Via child

if($('#myTable tr').length-1 == $(".someClass:checked").length)
{
    //Select parent
}

Via Parent

$('#select_all').click(function () {
    $('.someClass').prop('checked', this.checked)
});  

Thanks