Search code examples
c#jqueryasp.net-mvc-4checkboxclient-side-scripting

JQuery not selecting all in from checkbox


I cannot seem to get my JQuery working. I have attached my view which has a loop that shows every model in a table format. Each model has a checkbox beside it. The table head also has a checkbox item name/id as checkAll. I have referenced my JQuery script and added my function. I cannot get the function to work, when I click on the checkAll check box nothing happens. I'm extremely new to JQuery and cannot work this one out?

@model IEnumerable<MVC_Example2___ADO.Models.Employees>

@{
    ViewBag.Title = "Delete";
}
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript" >
</script>
<script type="text/javascript">
    $(function () {
        $("#checkAll").click(function () {
            $("input[name='EmployeeIDToDelete']").click(function () {
                if ($("input[name='EmployeeIDToDelete']").length == $("input[name='EmployeeIDToDelete']:checked").length) {
                    $("#checkAll").attr("checked", "checked");
                }
                else {
                    $("#checkAll").removeAttr("checked");
                }
            })
        })
    })
</script>
<html>
<body>
    @using (Html.BeginForm())
    {
        <table align="center" border="1" style="border:ridge;">
            <thead>
                <tr>
                    <td><input type="checkbox" id="checkAll" name="checkAll" /> </td>
                    <td>Photo</td>
                    <td>Name</td>
                    <td>Gender</td>
                </tr>
            </thead>
            <tbody>
                @Html.EditorForModel()
            </tbody>
        </table>
        <input type="submit" name="submit" value="Delete Entries" />
    }
</body>
</html>

Solution

  • A couple of things:

    1. You're adding the click handler of the row checkboxes inside the handler of the click on the header checkbox, so there will be no events triggered from the rows.
    2. You're improperly using attr() when you should probably be using prop() (properties vs attributes -- they are two different things).

    Here's how I would write this:

    $(function() {
      var $checkAll = $('#checkAll');
      var $inputs = $('input[name="EmployeeIDToDelete"]');
      
      $checkAll.click(function() {
        $inputs.prop('checked', this.checked);
      });
    
      $inputs.change(function() {
          $checkAll.prop('checked', $inputs.length == $inputs.filter(':checked').length);
      }).change();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    
    <input type="checkbox" id="checkAll" />
    
    <hr />
    
    <input type="checkbox" name="EmployeeIDToDelete" />
    <br/>
    <input type="checkbox" name="EmployeeIDToDelete" />
    <br/>
    <input type="checkbox" name="EmployeeIDToDelete" />
    <br/>
    <input type="checkbox" name="EmployeeIDToDelete" />
    <br/>