1

我有一组已经标记的动态复选框。当我单击其中一个时,应取消选中以下所有复选框,如果再次重新标记所有上述复选框标记。请问有人可以帮我吗?

谢谢你。

@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>
}

问题概述

4

3 回答 3

2

您可以在客户端使用javascript. 见例子。

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

于 2018-05-28T20:41:51.553 回答
1

创建复选框时,您需要将它们存储在一个数组中,并对它们使用相同的 onClick 函数,参数是数组中 Chekbox 的索引。

当用户点击它时,您只需要循环遍历数组并根据需要更改状态。

伪代码示例:

let _checkboxesArray = [];
function createDynamicCheckboxes() {
  _checkboxesArray = [];
  for(let i = 0; i < Model.transportDate.Count(); i ++) {
    _checkboxesArray[i] = 'cb' + i;
    // create your checkbox and assign it the id we just stored.
    dCheckbox.id = _checkboxesArray[i];
    let li = i;
    dCheckbox.onClick = (function(index) {
      for (let j = 0; j < Model.transportDate.Count(); j ++) {
        document.getElementById(_checkboxesArray[j]).checked = j < index;
      }
    }(li));
  }
}
于 2018-05-28T19:16:48.623 回答
0

如果选中该复选框,您可以使用 javascript 检查。

因此,如果选中该复选框,请取消选中其他复选框:

document.getElementById("checkbox").checked = true; document.getElementById("checkbox").checked = false;

于 2018-05-28T18:51:06.073 回答