views:

60551

answers:

9

I have a drop down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery. Using regular JavaScript, I would do something like:

ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it to.

However, I need to do this with jQuery because I'm using a CSS class for my selector (stupid ASP.NET client ids...).

Here are a few things I've tried:

$("._statusDDL").val(2); // doesn't find 2 as a value
$("._statusDDL").children("option").val(2) // also failed.

How can I do it with jQuery?

+35  A: 

jQuery's documentation states:

[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

This behavior is in jQuery versions 1.2 and above.

You most likely want this:

$("._statusDDL").val('2');
strager
+1. This alone is reason enough to use jQuery. Very useful!
Cam
Does this work if the `select` is hidden (`display: none;`)? I can't get it to work right...
Padel
+1  A: 

So as it turns out, I had it right the first time with:

$("._statusDDL").val(2);

When I put an alert just above it it works fine, but when I remove the alert and let it run at full speed, I get the error "Could not set the selected property. Invalid Index". I'm not sure if it's a bug with jQuery or IE6 (I'm guessing IE6), but it's terribly annoying.

Phairoh
Try making 2 a string, maybe?
strager
tried it, same thing
Phairoh
So I changed it so that now it executes after a 300 miliseconds using setTimeout. Seems to be working now. Thanks strager for your help.
Phairoh
A: 

Just try with

$("._statusDDL").val("2");

and not with

$("._statusDDL").val(2);

emas
A: 

How are you loading the values into the drop down list or determining which value to select? If you are doing this using ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.

If you are using one of jQuery's ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.

This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it taked longer than 300 ms.

Pervez Choudhury
+2  A: 

Just an FYI, you don't need to use CSS classes to accomplish this.

You can write the following line of code to get the correct control name on the client:

$("#<%= statusDDL.ClientID %>").val("2");

ASP.NET will render the control ID correctly inside the jQuery.

y0mbo
That only works when your javascript is inside of the .aspx or .ascx markup and not when it's in the .js file as was the case here. Also, depending on how deep your controls are nested in your application (in my case they were about 10 levels deep) the ClientID can get incredibly long and can actually add significant bloat to the size of your javascript if used too liberally. I try to keep my markup as small as possible, if I can.
Phairoh
All fair points!(and a good reason to move to ASP.NET MVC)
y0mbo
@y0mbo But even if you move to MVC you should still use external .JS files for your JavaScript so that browsers and proxy servers can cache it for performance.
Roberto Sebestyen
@Roberto - but MVC doesn't use the stupid naming conventions that asp.net webforms does so you can comfortably reference in an external js file to the controls you need.
lloydphillips
If you create OO-style javascript you can pass your client Ids into the constructor of your object. The object code is all contained in an external js file, but you instantiate it from your aspx code.
whatispunk
A: 

To set the drop down value as selected then it may help you. http://praveenbattula.blogspot.com/2009/08/jquery-how-to-set-value-in-drop-down-as.html

Rare Solutions
A: 

Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET CLient IDs - this might help you too:

<asp:DropDownList id="MyDropDown" runat="server" />

$("[id* = 'MyDropDown']").append("<option value='-1'>&nbsp;</option>"); //etc

Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"

AVH
+1  A: 

So I changed it so that now it executes after a 300 miliseconds using setTimeout. Seems to be working now. Thanks strager for your help.

– Phairoh

I have run into this many times when loading data from an ajax call. I too use .net and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the ajax call and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:

$.ajax({
                type: "POST",
                url: document.URL + '/PageList',
                data: "{}",
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

                    $('#locPage' + locId).find('option').remove();

                    $.each(pages, function () {
                        $('#locPage' + locId).append(
                            $('<option></option>').val(this.PageId).html(this.Name)
                        );
                    });
                }
            });
Keith
A: 

Why not use $("select[name$='MyDropDown']").val() ?

Monty
If you're matching on the name you might as well remove the `$` so it's a full match, not 'ending with'. But your suggestion is probably faster than only matching on a classname. Even faster though would be `element.classname` or `#idname`.
Alec