Ad

How To Ensure At Least One Checkbox Is Selected From The Table On Button Click Using JQuery In MVC?

- 1 answer

<tbody>
    @if (ViewBag.fileVMList != null)
    {
        @foreach (var item in ViewBag.fileVMList)
        {
            <tr>                      
                <td> @item.fileName </td>                     
                <td><input type="checkbox" class="chkCheckBoxId" value="@item.id" name="id"/>&nbsp;</td>
            </tr>
        }
    }
</tbody>


<script>
  //trigger on button click 
  var ConfirmRestore = function()
  {
  if ($('.chkCheckBoxId').prop('checked') == true) {
                $('#myModal').modal('show');
            }
            else
                alert("Please select record to restore!");
  }
</script>

The above code represents the portion of a table with 5 records and each record has a checkbox in Index.cshtml file (MVC). There is one master button and on the button click, the ID of the selected checkbox will be passed to the controller form the view for DELETION. If it is null, an error message should be displayed and empty values should NOT be passed! I want to ensure that at least one checkbox is selected on the button click event.

This is what I have tried so far but it is only checking for the first checkbox ONLY, how to check for all the checkbox?

Ad

Answer

Please use following script on button click event to check atleast on checkbox checked.

$("#btnSubmit_Id").click(function () {
                var checked_checkboxes = $("#tblElement_Id input[type=checkbox]:checked");
                if (checked_checkboxes.length == 0) {
                   alert("Please select record to restore!");
                }
                  $('#myModal').modal('show');
            });
</script>
Ad
source: stackoverflow.com
Ad