I encountered a small problem at work today. The situation is as follows. When I set the Enable value of Checkbox to false in the background page, I used a script (chk.disabled = false) in the front-end page and could not change disabled. The value is false and the code is as follows:
Front desk code:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function foo() { var chk = document.getElementById("<%=chkBlog.ClientID %>"); if (chk.disabled) { chk.disabled = false; } else { chk.disabled = true; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:CheckBox ID="chkBlog" runat="server" Text="http://owen-zhang.cnblogs.com"></asp:CheckBox> <asp:Button ID="btnCheck" runat="server" Text="Client check" OnClientClick="foo();return false;" /> </div> </form> </body> </html>
Backend code:
protected void Page_Load(object sender, EventArgs e) { this.chkBlog.Enabled = false; }
Why does this happen? Let us take a look at the source code of html, as follows:
<span disabled="disabled"> <input id="chkBlog" type="checkbox" name="chkBlog" disabled="disabled" /> <label for="chkBlog">http://owen-zhang.cnblogs.com</label> </span>
It turns out that when the Enable attribute of the Checkbox control is false, the output to Html becomes a set of controls (element), not one control as we expected.
Option 1:
In the above code, although we changed the disabled attribute of the chkBlog control to false, the disabled attribute of the parent node () of the chkBlog control is still disabled. This has a priority issue. Generally, the priority of the parent node is higher than that of the child node. Therefore, we need to change the disabled value of the parent node. The above client script code needs to be slightly modified, as follows:
<script type="text/javascript"> function foo() { var chk = document.getElementById("<%=chkBlog.ClientID %>"); if (chk.disabled) { chk.parentNode.disabled = false; chk.disabled = false; } else { chk.parentNode.disabled = true; chk.disabled = true; } } </script>
Only add the code highlighted above.
Option 2:
If you use option one, you must add an additional statement to change the disabled attribute of the parent node. When there are many places to modify, it will be more troublesome, and it does not conform to the general code logic and is redundant. code. Is there any other simpler way? Yes~, we only need to modify the background code, as follows:
protected void Page_Load(object sender, EventArgs e) { this.chkBlog.InputAttributes.Add("disabled", "disabled"); }
That is, we do not change the Enable attribute of Checkbox, but change the Html content output by Checkbox to the client through the attribute settings in InputAttributes, as follows:
<input id="chkBlog" type="checkbox" name="chkBlog" disabled="disabled" /> <label for="chkBlog">http://owen-zhang.cnblogs.com</label>
The previously "redundant" parent node is now gone.