选中特定 asp:CheckBoxList ListItem 时需要 asp:TextBox

Require asp:TextBox when specific asp:CheckBoxList ListItem checked

我没有找到任何要求在选中 CheckBoxList 中的特定复选框时填写文本框的示例。我发现了很多独立复选框的例子。我知道 CheckBoxList 是一种独特的动物,没有内置的必需验证器。

我需要用户在选中复选框列表中的 "Other" 框时完成相关的文本框。 show/hide 基于该框的文本框也被选中会很好。

当所有其他方法都失败时,创建一个 CustomValidator。有了它,您可以编写自己的规则来判断一个元素或多个元素何时有效。但是为了使它起作用,我将 checkBoxListValidator class 添加到 CheckBoxList 以便能够使用 jQuery.

找到它
<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="checkBoxListValidator">
    <asp:ListItem Text="Option A" Value="1"></asp:ListItem>
    <asp:ListItem Text="Option B" Value="2"></asp:ListItem>
    <asp:ListItem Text="Option C" Value="3"></asp:ListItem>
    <asp:ListItem Text="Other" Value="-1"></asp:ListItem>
</asp:CheckBoxList>

<asp:TextBox ID="TextBox1" runat="server" Style="display: none"></asp:TextBox>

<asp:CustomValidator ID="CustomValidator1" runat="server" Text="Please fill out the TextBox" ClientValidationFunction="requiredFieldIfOther"></asp:CustomValidator>

<script type="text/javascript">
    function requiredFieldIfOther(sender, element) {
        var isValid = true;
        var textBoxToValidate = $("#<%= TextBox1.ClientID%>");
        $('.checkBoxListValidator input[type="checkbox"]').each(function () {
            if ($(this).val() == "-1" && $(this).prop("checked") == true && textBoxToValidate.val() == "") {
                isValid = false;
            }
        });
        element.IsValid = isValid;
    }

作为奖励,代码显示和隐藏基于 other 复选框的文本框。

    $('.checkBoxListValidator input[type="checkbox"]').change(function () {
        var textBoxToValidate = $("#<%= TextBox1.ClientID%>");
        if ($(this).val() == "-1" && $(this).prop("checked") == true) {
            textBoxToValidate.prop("style", "display:block");
        } else {
            textBoxToValidate.prop("style", "display:none");
        }
    });
</script>