asp.net Javascript獲取CheckBoxList的value
2024-07-10 12:42:56
供稿:網(wǎng)友
以后我會(huì)陸續(xù)的寫出這段時(shí)間中學(xué)習(xí)到的東西,與大家一起分享。這篇文章也算是工作中的一個(gè)筆記吧,希望給遇到同樣問題的朋友,一點(diǎn)小小的幫助。
在 開發(fā)工作中,因?yàn)橐鲇玫紺heckBoxList在客戶端用js操作,無論js怎樣調(diào)試,就是無法獲取value的值,很是郁悶,后來Google了下,去了趟CodeProject,算是幸運(yùn)的。我們?cè)诰W(wǎng)頁上放置一下代碼:
代碼如下:
<asp:CheckBoxList runat="server" ID="chkDemo" RepeatDirection="Horizontal" RepeatLayout="Flow"> <asp:ListItem Text="測試A" Value="A"></asp:ListItem>
<asp:ListItem Text="測試B" Value="B"></asp:ListItem>
<asp:ListItem Text="測試C" Value="C"></asp:ListItem>
<asp:ListItem Text="測試D" Value="D"></asp:ListItem>
<asp:ListItem Text="測試E" Value="E"></asp:ListItem>
</asp:CheckBoxList>
當(dāng)瀏覽器呈現(xiàn)這段代碼后,我們?cè)倏纯词鞘裁礃拥腍tml腳本:
<table id="chkDemo" border="0">
<tr><td><input id="chkDemo_0" type="checkbox" name="chkDemo$0" /><label for="chkDemo_0">測試A</label></td>
<td><input id="chkDemo_1" type="checkbox" name="chkDemo$1" /><label for="chkDemo_1">測試B</label></td>
<td><input id="chkDemo_2" type="checkbox" name="chkDemo$2" /><label for="chkDemo_2">測試C</label></td>
<td><input id="chkDemo_3" type="checkbox" name="chkDemo$3" /><label for="chkDemo_3">測試D</label></td>
<td><input id="chkDemo_4" type="checkbox" name="chkDemo$4" /><label for="chkDemo_4">測試E</label></td> </tr></table>
這段Html腳本會(huì)因?yàn)镽epeatLayout的設(shè)置有所差異,但是都有一個(gè)共同點(diǎn),就是 生成的CheckBox沒有value屬性,
所以在客戶端用js是沒辦法獲取值的
為了解決這個(gè)問題,我們需要擴(kuò)展一下CheckBoxList:這是我在CodeProject上找到的源碼,時(shí)間久了,鏈接就不貼了吧。
代碼如下:
[ToolboxData("<{0}:CheckBoxListEx runat=/"server/"></{0}:CheckBoxListEx>")]
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;