如果取消选中一个复选框,如何取消选中以下所有复选框

时间:2018-05-28 18:26:24

标签: javascript c# asp.net checkbox checkboxfor

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

谢谢。

@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

3 个答案:

答案 0 :(得分:2)

您可以使用javascript在客户端进行此操作。见例。

&#13;
&#13;
$('#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
    });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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));
  }
}

答案 2 :(得分:0)

You can check with javascript if the checkbox is checked.

So, if the checkbox is checked, uncheck the others:

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

相关问题