user603007
user603007

Reputation: 11804

Why is the asp.net checkbox not disabled?

I am trying to set the disabled property for my CheckBox to true. However, when I do a postback the CheckBox is still enabled?

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<head runat="server">
    <title></title>
    <script>
        $(document).ready(
            function () {
                $("#CheckBoxList1_0").attr('disabled',true);
            }
    );
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem>een</asp:ListItem>
            <asp:ListItem>twee</asp:ListItem>
            <asp:ListItem>drie</asp:ListItem>
        </asp:CheckBoxList>
    </div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </form>
</body>
</html>

c#:

 protected void Button1_Click(object sender, EventArgs e)
        {
            if (!CheckBoxList1.Items[0].Enabled)
            {
                Response.Write("it is disabled");

            }
        }

Upvotes: 1

Views: 1576

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83376

CSS properties like disabled added with jQuery, or added in any way for that matter, will not post to the server when you do a postback.

If you really need to keep track of which checkboxes are disabled, one way to accomplish this would be to store those elements' ids into a hidden input, the value of which will post to the server.

Something like this should work

<input type="hidden" runat="server" id="yourHiddenInput" />

$("form").submit(function(){
    var allIds = [];
    $("input[type='checkbox']:disabled").each(function() {
       allIds.push($(this).attr("id"));
    });
    $("#yourHiddenInput").val(allIds.join());

    //form is about to post.  When it does, 
    //you'll be able to read the ids via yourHiddenInput.Value
});

Upvotes: 2

Daniel Powell
Daniel Powell

Reputation: 8303

When you change the checkbox using javascript that change is on the client only, I believe that the viewstate information for the checkbox won't be updated and so when the postback occurs as far as the page knows the checkbox is still unchecked

Upvotes: 1

Related Questions