【问题标题】:How to ensure at least one checkbox is selected from the table on button click using jQuery in MVC?如何确保在 MVC 中使用 jQuery 在按钮单击时从表中选择至少一个复选框?
【发布时间】:2020-03-03 07:47:07
【问题描述】:
<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>

上面的代码代表了一个有 5 条记录的表格部分,每条记录在 Index.cshtml 文件 (MVC) 中都有一个复选框。有一个主按钮,单击按钮时,选定复选框的 ID 将通过视图传递给控制器​​以进行删除。如果为 null,则应显示错误消息并且不应传递空值!我想确保在按钮单击事件上至少选中一个复选框。

这是我迄今为止尝试过的,但它只检查第一个复选框,如何检查所有复选框?

【问题讨论】:

  • 将您的条件包装到按钮的单击处理程序中(看不到任何内容)
  • @johnSmith 请查看更新后的脚本。以下是按钮点击事件的触发。
  • $('.chkCheckBoxId').prop('checked') == true 更改为$(".chkCheckBoxId:checked").length &gt; 0

标签: javascript jquery asp.net-mvc razor


【解决方案1】:

请在按钮单击事件上使用以下脚本来检查至少选中的复选框。

$("#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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多