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 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 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.

<script type="text/javascript">
        function getDropDownList1Value()
            var SelectedVal = $('#< %=<strong>DropDownList1.ClientID %>').val();
            return SelectedVal;

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 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:


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.

Hope that helps.


, , ,

One Response to Get ASP.NET DropDownList Selected Value with jQuery

  1. Naveed February 26, 2009 at 6:50 am #

    Hi its good piece of work also I’ve seem some good work with web service and Jquery here, have a look to this please here.

Powered by WordPress. Designed by Woo Themes