Retrieve the Value of an ASP.NET CheckBox in jQuery

In this post, let us see how to retrieve the text of an ASP.NET CheckBox using jQuery

Declare an ASP.NET CheckBox control as shown below:

<asp:CheckBox ID="cb1" runat="server" Text="Option One" />

Now a lot of users try to retrieve the text of this checkbox in the following manner:

alert($("#Checkbox1").val());

However this code does not work for an ASP.NET Checkbox control. Let us see why. This control renders to the following HTML

<input id="Checkbox2" type="checkbox" name="cb1" />
<
label for="cb1">Option One</label>

If you observe, a label control gets created which holds the text for the CheckBox.

In order to retrieve the text of this checkbox, change the jQuery code to:

alert($("input:checkbox[id$=cb1]").next().text());

and now the code would alert ‘Option One’

Note: The same code could have also been written as alert($("#cb1").next().text()). However the code given above works in the case of a MasterPage too. I prefer the above one!






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: