BloggerAds

2011年7月27日 星期三

用jQuery取得RadioButtonList所選的值

開發.NET程式時,常常會使用到RadioButtonList控制項,在很多狀況下常需要依照使用者所選的值去做一些判斷或動作,雖然.Net本身就有OnSelectedIndexChanged事件可以用,搭配UpdatePanel等,可以做到不用PostBack的功能,但用jQuery也是可以寫的很簡單。

若使用的是RadioButtonList控制項,aspx內容如下:

<asp:RadioButtonList ID="rblTest" runat="server" >
    <asp:ListItem Text="1" Value="1" Selected="True" />
    <asp:ListItem Text="2" Value="2" />           
</asp:RadioButtonList>
產生的Html語法會長成這個樣子:
<table id="rblTest" border="0">
<tr>
<td><input id="rblTest_0" type="radio" name="rblTest" value="1" checked="checked" /><label for="rblTest_0">1</label></td>
</tr><tr>
<td><input id="rblTest_1" type="radio" name="rblTest" value="2" /><label for="rblTest_1">2</label></td>
</tr>
</table>
有看到吧? 產生的input物件,name 都是 rbTest,但id卻是以rbTest_開頭,再加上從0開始的序號,所以如果要使用jQuery取得所選的值的話,可以有兩種方法:
1.用id開頭取得:
$("input[id^='<% =rblTest.ClientID %>']:checked").val()
2.用name取得:
$("input[name='<% =rblTest.ClientID %>']:checked").val()
兩種都可以試試。

1 則留言: