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!

5
  • 2
    IDs are unique, you cannot have same ID (someDivId) multiple times. You should change them to class. Commented Jul 27, 2017 at 13:19
  • Possible duplicate of Can multiple different HTML elements have the same ID if they're different elements? Commented Jul 27, 2017 at 13:19
  • 1
    you can take class attribute and apply prop function on it Commented Jul 27, 2017 at 13:20
  • You may try a different selector. Eg.: $('.table td [type="checkbox"]').prop('checked', c) Commented Jul 27, 2017 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. Commented Jul 27, 2017 at 23:09

2 Answers 2

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)
});  
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly! Thanks. I'll mark it answered as soon as it lets me.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.