Search code examples
javascriptc#asp.netcheckboxcheckboxfor

How to uncheck all below checkboxes when one checkbox is unchecked


I have a dynamic set of checkboxes which are already mark. When I click one out of it then all the below checkboxes should be unchecked and if re mark again all the above checkbox mark again. Is there anyone who can help me on this please?

Thank you.

@for (int i = 0; i < Model.transportDate.Count(); i++)
{
                    <tr>
                        <td>
                            @Html.CheckBoxFor(Model => Model.transportDate[i].selection)
                        </td>
                        <td>
                            @Html.TextBoxFor(Model => Model.transportDate[i].Date)
                        </td>
                    </tr>
}

Overview of question


Solution

  • You can do it on the Client side using javascript. See example.

    $('#tbl [type=checkbox]').click(function() {
      var $this = this; //save clicked chk
      if ($(this).is(':checked')) //nothing to do
        return;
      var uncheck = false;
      $(this).parents('table') //get container
        .find('[type=checkbox]') //get siblings
        .each(function() { //iterate
          if (this === $this) //found
            uncheck = true;
          if (uncheck)
            this.checked = false; //clear checkbox
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="tbl">
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
      <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td>other</td>
      </tr>
    </table>