【问题标题】:iterating over a table of checkboxes with jquery使用 jquery 遍历复选框表
【发布时间】:2012-12-28 20:56:09
【问题描述】:

我在我的 asp.net mvc 视图中有一个这样的表:

<table>
  <tr>
   <td>Option 1<td>
   <td>Option 2<td>
   <td>Option 3<td>
   <td>Option 4<td>
  <tr>
foreach(var options in Model)
 {
  <tr>
   <td>@Html.ChecBoxFor(x => x.one)<td>
   <td>@Html.ChecBoxFor(x => x.two)<td>
   <td>@Html.ChecBoxFor(x => x.three)<td>
   <td>@Html.ChecBoxFor(x => x.four)<td>
  <tr>
 }
<table>

我试图弄清楚如何遍历每一行,然后有条件地切换某些复选框。例如,如果选中复选框 1,则确保未选中复选框 4,反之亦然。该条件将分别适用于复选框二和三。

【问题讨论】:

  • 类似于单选按钮的功能?

标签: c# jquery asp.net asp.net-mvc razor


【解决方案1】:

在 JSFiddle 中尝试过。陈词滥调看demo

    $(function() {
    $("#btn").click(function() {
        $("tr").each(function() {
            var $RowCheckBoxes = $(this).find("input:checkbox");

            // if checkbox one is checked then make sure checkbox four is unchecked
            if ($RowCheckBoxes.eq(0).is(':checked') == true) {
                $RowCheckBoxes.eq(3).prop("checked", false);
            }

            // The conditon would apply to checkboxes two and three respectively.
            if ($RowCheckBoxes.eq(1).is(':checked') == true) {
                $RowCheckBoxes.eq(2).prop("checked", false);
            }
        });
    });
});

【讨论】:

  • 这对我有用。我进行了一项更改,以便它可以即时检查。我将 $("btn").click 更改为 $("input:checkbox").change.
【解决方案2】:

你不需要 jquery 来完成这个基本任务,只需给你的复选框起一个名字:

var chk = document.getElementsByName("theName");
for(var i = 0; i < chk.length; i++){
  chk[i].whateverYouWant;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 2011-03-16
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多