开发者社区 问答 正文

如何验证组中只有一个复选框等于“真”

我如何强制选择复选框中只有一个选项等于组的“真”?它可以与jQuery或数据注释一起使用...

因为目前你可以提交所有的错误,我不想允许这样,我希望只有一个必须并且需要是真的,否则提交将不起作用。

<div class="row">
    @Html.LabelFor(model => model.Question1CB1, htmlAttributes: new { @class = "control-label col-sm-2" })
    <div class="col-sm-1">
        <div class="checkbox">
            @Html.CheckBoxFor(model => model.Question1CB1, new { @class = "Question1CBs" })
            @Html.ValidationMessageFor(model => model.Question1CB1, "", new { @class = "text-danger" })
        </div>
    </div>

    @Html.LabelFor(model => model.Question1CB2, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-sm-1">
        <div class="checkbox">
            @Html.CheckBoxFor(model => model.Question1CB2, new { @class = "Question1CBs" })
            @Html.ValidationMessageFor(model => model.Question1CB2, "", new { @class = "text-danger" })
        </div>
    </div>

    @Html.LabelFor(model => model.Question1CB3, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-sm-1">
        <div class="checkbox">
            @Html.CheckBoxFor(model => model.Question1CB3, new { @class = "Question1CBs" })
            @Html.ValidationMessageFor(model => model.Question1CB3, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

复选框已经工作,只能选择其中一个

<script>
    $(document).ready(function () {
        $('.Question1CBs').click(function () {
            $('.Question1CBs').not(this).prop('checked', false);
        });
    });
</script>

展开
收起
sossssss 2019-12-09 17:44:50 1419 分享 版权
阿里云 AI 助理回答

要实现这个功能,你可以使用jQuery来确保在一组复选框中只有一个被选中。这里是一个简单的示例,展示了如何通过监听复选框的change事件来实现这一需求:

首先,在你的HTML页面中确保已经引入了jQuery库。如果还没有,可以通过以下方式引入:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

然后,添加一个jQuery脚本来控制复选框的行为:

<script>
    $(document).ready(function () {
        $('.Question1CBs').on('change', function () {
            // 当一个复选框被选中时
            if ($(this).is(':checked')) {
                // 先取消其他同组复选框的选中状态
                $('.Question1CBs').not(this).prop('checked', false);
            }
        });
    });
</script>

这段脚本会在文档加载完成后,为所有拥有Question1CBs类的复选框绑定一个change事件处理器。当用户改变任何一个复选框的状态时,它会检查是否被选中,如果是,则取消同一组内其他复选框的选中状态。

这种方法是在客户端(即浏览器)上执行的即时验证,可以立即给予用户反馈。然而,为了确保数据的完整性和安全性,你还需要在服务器端进行验证。在ASP.NET MVC中,可以通过自定义模型验证属性来实现这一点,但请注意,这个问题的解决方案主要集中在前端交互上,确保单选逻辑的实现。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答分类:
问答地址: