Advert

Main

Get ASP.NET DropDownList Selected Value with jQuery

With Microsoft’s recent announcement that they will begin shipping jQuery with Visual Studio, the little Javascript framework is about to hit the big time (it was already sort of big time, but this is BIG TIME). And rightfully so.

I have been a Prototype and Scriptaculous user for over a year now. But I am starting the transition over to jQuery, and am loving what I see. The learning curve is easy if you’re coming in from one of the other frameworks, so don’t sweat it.

If you’re an ASP.net programmer and you use server controls, then you know that ASP changes the control ID into something that the server will be able to understand on postbacks. This makes it a little tricky to reference these controls with Javascript on the client.

The ASP Trick

Well, here’s a neat little trick that I picked up on one of the forums that will allow you to get the value of an ASP.net dropdownlist using jQuery. Place the following Javascript function at the bottom of your .aspx file. I think you’ll need to have it after your DropDownList to insure that it works properly.

The jQuery part of this function is shown in blue here: $(‘#<%=DropDownList1.ClientID %>‘).val()

The real magic is the red part. This is ASP code that will be processed on the server to write the control’s Client ID into the function. Given such a small amount of jQuery, you could easily pull out the jQuery code and use it with other frameworks or plain old JScript as well. The key after all, is getting your Javascript to know what the control’s DOM ID is.

Using the function is as simple as:

var myValue = getDropDownList1Value();

This could, of course, be used with any ASP.net server control for other purposes as well.

A jQuery Alternative: The CSS Class Selector

Another alternative with jQuery, would be to assign a css class to the control and use that class as your selector. Here’s a jQuery example to select on a css class called mydropdown:

$(‘.mydropdown’).val();

Just assign the mydropdown class to your ASP control in Visual Studio and jQuery will find your control. But be careful…jQuery will find every control that has that class, so give a unique class to each control you want to try this with.

About WhyPad!

WhyPad is not affiliated with any of the companies mentioned here. It is a place where I capture things that may be of use to myself or others in the future. The information here is provided without any promise of warranty or accuracy. But I try to get it right!