【问题标题】:Auto disable other checkboxes using html.checkboxfor once one is selected一旦选中一个复选框,使用 html.checkboxfor 自动禁用其他复选框
【发布时间】:2016-04-13 08:27:44
【问题描述】:

我正在尝试在选择一个复选框时禁用其他复选框,如果再次取消选择该复选框,则再次启用。
以下是我发现在标准复选框的示例小提琴中工作的代码 sn-p但是我无法为复选框复制此内容,有人可以推荐我需要进行的更改以使其在复选框中起作用吗?

    <script>
    $('#chkItems').change(function () {
        $(this).siblings('#chkItems').prop('disabled', this.checked)
    });
   </script>

下面是我的复选框,我在哪里调用它

@Html.CheckBoxFor(modelItem => item.IsDisplayImage, new { id = "chkItems" })

【问题讨论】:

  • 为什么不用收音机?
  • 收音机会自动取消选择其他选项吗?
  • 是的,每次只能选择一个
  • 正如@guradio 所说,最好使用单选按钮...只需将它们设置在一个单选组中(单选按钮必须具有相同的名称才能在一个单选按钮组中)
  • @cg91 ,检查这个问题stackoverflow.com/questions/22174475/…

标签: javascript jquery html razor checkboxfor


【解决方案1】:

如果想使用复选框持久化,您可以使用此代码,否则最好使用单选按钮

HTML

<label class="checkbox-inline check">
      <input type="checkbox" name="skills" id="radio" value="1"> 1
</label>
<label class="checkbox-inline check">
      <input type="checkbox" name="skills" value="2"> 2
</label>
<label class="checkbox-inline check">
      <input type="checkbox" name="skills" value="3"> 3
</label>

JS:

$('.check input:checkbox').click(function() {
    $('.check input:checkbox').not(this).prop('checked', false);
});  

检查这个 jsfiddle 以获取 demo

您可以将单选按钮用作:

<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other  
</form> 

【讨论】:

  • 谢谢,但我如何使用@html.checkboxfor 或radiobuttonfor 来做到这一点?
【解决方案2】:

好的。例如你有模型ForRadioButtonsModel 喜欢

public class ForRadioButtonsModel
    {
        public int Id { get; set; }
        public bool IsDisplayImage { get; set; }
    }

在查看时您传递了此模型的集合或包含此集合的模型

return View((List&lt;ForRadioButtonsModel&gt;) collection);

在视图中你可以做下一步来创建 RadioGroup

@foreach (var item in Model) <-- Model is of type List<ForRadioButtonsModel>
{
     @Html.RadioButtonFor(m => item.IsDisplayImage, item.IsDisplayImage) 
}

这将呈现下一个 HTML

<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="True">
<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="False">

所以您将拥有同名但具有不同值的单选按钮

【讨论】:

  • 好吧,我刚刚意识到我可能不得不在某个阶段将 isdisplayimage 传回为 null(即没有选择值),这仍然可以使用单选按钮吗?
猜你喜欢
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2020-09-02
  • 2011-05-24
  • 2022-01-25
  • 2018-01-16
相关资源
最近更新 更多