asp.net Javascript获取CheckBoxList的value 以后我会陆续的写出这段时间中学习到的东西,与大家一起分享。这篇文章也算是工作中的一个笔记吧,希望给遇到同样问题的朋友,一点小小的帮助。 在 开发工作中,因为要做用到CheckBoxList在客户端用js操作,无论js怎样调试,就是无法获取value的值,很是郁闷,后来Google了下,去了趟CodeProject,算是幸运的。我们在网页上放置一下代码: 复制代码 代码如下: 当浏览器呈现这段代码后,我们再看看是什么样的Html脚本:
这段Html脚本会因为RepeatLayout的设置有所差异,但是都有一个共同点,就是 生成的CheckBox没有value属性, 所以在客户端用js是没办法获取值的 为了解决这个问题,我们需要扩展一下CheckBoxList:这是我在CodeProject上找到的源码,时间久了,链接就不贴了吧。 复制代码 代码如下: [ToolboxData("<{0}:CheckBoxListEx runat=\"server\">")] public class CheckBoxListEx : CheckBoxList,IRepeatInfoUser { void IRepeatInfoUser.RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) { string clientID = UniqueID + this.ClientIDSeparator + repeatIndex.ToString(NumberFormatInfo.InvariantInfo); //var writer.WriteBeginTag("input"); writer.WriteAttribute("type", "checkbox"); writer.WriteAttribute("name", UniqueID + this.IdSeparator + repeatIndex.ToString(NumberFormatInfo.InvariantInfo)); writer.WriteAttribute("id", clientID); writer.WriteAttribute("value", Items[repeatIndex].Value); if (Items[repeatIndex].Selected) writer.WriteAttribute("checked", "checked"); System.Web.UI.AttributeCollection attrs = Items[repeatIndex].Attributes; foreach (string key in attrs.Keys) { writer.WriteAttribute(key, attrs[key]); } writer.Write("/>"); writer.Write(""); } 上边的这段代码是我经过修改的,与原著中有些差别:clientID的生成以及Checked属性的添加等,我想这段代码不需要再详细的讲解了吧。 把它编译成单独的类,在Toolbox上会自动出现,像使用那个正常的CheckBoxList一样,拖动到页面就可以了。 在客户端,我们js取值大致如下: 复制代码 代码如下: 结束