我们制作表单的时候都会用到多选CheckBox和单选RadioButton按钮。
有的时候我们希望它们的默认值不可以让用户改变。
最普遍的方法就是加上 enable=false。但这样就有了个问题,原本定义好的样式不见了!CheckBox变的很难看。
如何让CheckBox默认值不变,又不丢失原来的样式呢?
很简单,只要在每个CheckBox上添加属性onclick="this.checked=!this.checked;"
就是在用户改变了它之后再给改回去。
foreach (Control c in Page.Controls)
...{
if (c.GetType().ToString() == "System.Web.UI.WebControls.CheckBoxList")
...{
foreach (ListItem l in ((CheckBoxList)c).Items)
...{
l.Attributes.Add("onclick", "this.checked=!this.checked");
}
}
}RadioButton就要复杂一点了!
foreach (Control c in Page.Controls)
...{
if (c.GetType().ToString() == "System.Web.UI.WebControls.RadioButtonList")
...{
//根据分析代码,我们看到单个的radio有唯一的id属性而且是这一个RadioButtonList控件的id+“_”+Index,所以第一步我们很容易找到这组radio被选中的radio的id
string radioId = ((RadioButtonList)c).ClientID +"_"+ ((RadioButtonList)c).SelectedIndex.ToString();
foreach (ListItem l in ((RadioButtonList)c).Items)
...{
//添加onclick事件,在用户改变了默认值后,再恢复本组默认的选中值
l.Attributes.Add("onclick","document.getElementById(""+radioId+"").checked=true");
}
}
}
本文介绍了一种方法,可以在保持CheckBox和RadioButton默认选中状态的同时,维持其原有的样式。通过简单的JavaScript代码实现,使得用户无法更改这些选项的默认设置。
2251

被折叠的 条评论
为什么被折叠?



