886

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

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?


Update

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

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

When I put an alert just above 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 Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
phairoh
  • 9,937
  • 4
  • 21
  • 18
  • 22
    The problem here ended up being an issue with IE6. I was creating new option elements for the select element and then trying to set the value to one of those newly created option elements. IE6 incorrectly waits until it has gotten control back from a script to actually create the new elements in the DOM so effectively what was happening is I was trying to set the drop down lists to options that did not exist yet, even though they should have. – phairoh Apr 22 '09 at 21:01
  • you could use pure javascript `dd1 = document.getElementsByClassName('classname here'); dd1.value = 2;` – user2144406 Feb 23 '16 at 20:41
  • http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/ –  May 25 '16 at 19:09

17 Answers17

1049

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');
javiniar.leonard
  • 528
  • 8
  • 22
strager
  • 84,025
  • 24
  • 129
  • 172
  • 22
    Does this work if the `select` is hidden (`display: none;`)? I can't get it to work right... – Padel Jul 13 '10 at 15:10
  • 11
    This just saved me from writing stuff like `$('._statusDDL [value="2"]').attr('selected',true);` Thanks! – Basil Sep 07 '11 at 13:48
  • In the latests version of JQuery it is recommanded to use $('select.foo option:selected').val(); (http://api.jquery.com/val/) – Nordes Aug 08 '12 at 14:52
  • 6
    @Nordes that would be the case if getting the selected value. In this case it is setting the selected value, or more accurately, setting the selected option. – Jon P Aug 22 '12 at 00:41
  • 2
    What if you have the same value for two options??? see note section of [this](http://stackoverflow.com/a/10640466/415865) answer. – Vikas Apr 04 '13 at 05:17
  • 113
    @JL: You need to add `.change()` to see the option in the dropdown list frontend, i.e. `$('#myID').val(3).change();` – Avatar Aug 10 '13 at 09:43
  • 10
    Chaining the .change() should be added to the answer. I thought I was going insane with this solution not working until I read down through the comments. – David Baucum Jan 07 '15 at 20:33
  • appending .change() solves my problem. What I observed when using only val it just set value discard all other option, appending change() set the value andkeping all other option as well. – Prateek Sep 11 '15 at 07:52
  • 2
    `.change()` is also necessary to trigger any events that might be attached to the select's onchange. – Chris Harrison Aug 23 '16 at 10:30
151

With hidden field you need to use like this:

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

or

$("._statusDDL").val(2).change();
Aivar Luist
  • 1,561
  • 1
  • 9
  • 2
32

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
  • 4,492
  • 6
  • 37
  • 45
  • 8
    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 Apr 22 '09 at 20:49
  • 2
    @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. – 7wp Dec 15 '09 at 18:03
  • 1
    @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 Jan 20 '10 at 01:50
  • 6
    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. – mikesigs May 06 '10 at 16:33
  • 1
    I'd sooner set ClientIDMode="Static" on the asp controls so you know the ID will be the ID you specified. You have to be careful if you're then putting that control in a repeater though. http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx – Shawson Sep 24 '12 at 09:16
28

These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.

Things are a little more complicated if this isn't the case.

To read the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex");

To set the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex", 1);

Note that the prop() feature requires JQuery v1.6 or later.

Let's see how you would use these two functions.

Supposing you had a drop down list of month names.

<select id="listOfMonths">
  <option id="JAN">January</option>
  <option id="FEB">February</option>
  <option id="MAR">March</option>
</select>

You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:

<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />

And here's the JavaScript which these buttons would run:

function btnPrevMonth_Click() {
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    if (selectedIndex > 0) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
    }
}
function btnNextMonth_Click() {
    //  Note:  the JQuery "prop" function requires JQuery v1.6 or later
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    var itemsInDropDownList = $("#listOfMonths option").length;

    //  If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
    if (selectedIndex < (itemsInDropDownList - 1)) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
    }
}

My site is also useful for showing how to populate a drop down list with JSON data:

http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm

TylerH
  • 19,065
  • 49
  • 65
  • 86
Mike Gledhill
  • 23,658
  • 6
  • 133
  • 143
27

Just try with

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

and not with

$("._statusDDL").val(2);
Iswanto San
  • 17,245
  • 11
  • 56
  • 77
emas
  • 648
  • 7
  • 16
20

After looking at some solutions, this worked for me.

I have one drop-down list with some values and I want to select the same value from another drop-down list... So first I put in a variable the selectIndex of my first drop-down.

var indiceDatos = $('#myidddl')[0].selectedIndex;

Then, I select that index on my second drop-down list.

$('#myidddl2')[0].selectedIndex = indiceDatos;

Note:

I guess this is the shortest, reliable, general and elegant solution.

Because in my case, I'm using selected option's data attribute instead of value attribute. So if you do not have unique value for each option, above method is the shortest and sweet!!

Vikas
  • 22,508
  • 34
  • 110
  • 159
ISIK
  • 201
  • 2
  • 2
  • 5
    This is the correct answer, and everyone who did not say 'selectedIndex' instantly, should know better. Hurray DOM API and the people who wrote it back in the stone age. – vsync May 06 '13 at 18:00
16

I know this is a old question and the above solutions works fine except in some cases.

Like

<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>

So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use

jQuery("#select_selector").val(3);

You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.

<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>

and it gets the last value as "4" in sever side language.

SO MY FINAL SOLUTION ON THIS REGARD

newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');  

EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.

So what I do is actually ,removed the selected attribute and then make the new one as selected.

I would appreciate comments on this from senior programmers like @strager , @y0mbo , @ISIK and others

Rocker Maruf
  • 449
  • 5
  • 6
11

If we have a dropdown with a title of "Data Classification":

<select title="Data Classification">
    <option value="Top Secret">Top Secret</option>
    <option value="Secret">Secret</option>
    <option value="Confidential">Confidential</option>
</select>

We can get it into a variable:

var dataClsField = $('select[title="Data Classification"]');

Then put into another variable the value we want the dropdown to have:

var myValue = "Top Secret";  // this would have been "2" in your example

Then we can use the field we put into dataClsField, do a find for myValue and make it selected using .prop():

dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');

Or, you could just use .val(), but your selector of . can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:

dataClsField.val(myValue);
vapcguy
  • 5,607
  • 1
  • 45
  • 43
4

So I changed it so that now it executes after a 300 miliseconds using setTimeout. Seems to be working now.

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)
            );
        });
    }
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
clockwiseq
  • 4,049
  • 8
  • 33
  • 57
3

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,505
  • 1
  • 11
  • 7
3
<asp:DropDownList id="MyDropDown" runat="server" />

Use $("select[name$='MyDropDown']").val().

Iswanto San
  • 17,245
  • 11
  • 56
  • 77
Monty
  • 31
  • 1
  • 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 Oct 07 '10 at 20:37
3

I use an extend function to get client ids, like so:

$.extend({
    clientID: function(id) {
        return $("[id$='" + id + "']");
    }
});

Then you can call ASP.NET controls in jQuery like this:

$.clientID("_statusDDL")
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jonofan
  • 321
  • 4
  • 14
3

Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.

Mych
  • 2,419
  • 2
  • 31
  • 58
2

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 took longer than 300 ms.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pervez Choudhury
  • 2,758
  • 3
  • 23
  • 26
1
<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
     <asp:ListItem Value="1" Text="aaa"></asp:ListItem>
     <asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>

ClientIDMode="Static"

$('#DropUserType').val('1');
hamze shoae
  • 763
  • 7
  • 10
1

In my case I was able to get it working using the .attr() method.

$("._statusDDL").attr("selected", "");
Colin
  • 1,188
  • 11
  • 18
0

Pure JS

For modern browsers using CSS selectors is not a problem for pure JS

document.querySelector('._statusDDL').value = 2;

function change() {
  document.querySelector('._statusDDL').value = 2;
}
<select class="_statusDDL">
  <option value="1" selected>A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

<button onclick="change()">Change</button>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241