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:


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:


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!

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: