185

How do I set the index of a dropdown in jQuery if the way I'm finding the control is as follows:

$("*[id$='" + originalId + "']") 

I do it this way because I'm creating controls dynamically and since the ids are changed when using Web Forms, I found this as a work around to find me some controls. But once I have the jQuery object, I do not know how to set the selected index to 0 (zero).

hello_there_andy
  • 2,039
  • 2
  • 21
  • 51
oz.
  • 2,153
  • 3
  • 16
  • 15

11 Answers11

385

First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.

$(".myselect")

To answer your question though, there are a few ways to change the select elements value in jQuery

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;

// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
gnarf
  • 105,192
  • 25
  • 127
  • 161
  • is there a better way to do it? I figured it'd scan the whole DOM looking to match the ID, but since I'm new to jQuery I figured, let's make it work and then see if there's a better way to do it. Any advise will be appreciated. – oz. Aug 21 '09 at 22:57
  • Yes - if you can assign a class to the element(s) you need to find, it would be a much faster selector. – gnarf Aug 21 '09 at 23:07
  • @gnarf aren't IDs faster? – KBN Jul 25 '14 at 07:54
  • `#an-id` is faster, but `*[id$=ends-with]` is way slower, thats what the "assign a class to the element" is meaning – gnarf Aug 01 '14 at 01:52
  • How about if I have multiple ASP.net DropDownList with different selected index value? – SearchForKnowledge Apr 15 '15 at 14:34
  • Correct answer, but also check answer of PaulG: To make the dropbox update visually as well, `$("select#elem").val('0').change()` can be used for _both_ selecting and updating the UI. – Christopher Lörken Oct 28 '16 at 07:31
  • How to scroll to first element of multiselect in IE, but preserving all elements selected?? – Alexander Jan 06 '17 at 09:49
  • if you can't add a class to the element(s), `$("select[id$='" + originalId + "']")` is at least oodles faster than `$("*[id$='" + originalId + "']")` – Jay Irvine Aug 13 '18 at 17:26
  • the last option is the best imo – pstanton Oct 08 '21 at 20:22
110

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Addendum

As recommended in the comments use :

$("select#elem").prop('selectedIndex', 0);

4imble
  • 13,979
  • 15
  • 70
  • 125
  • 33
    And as of jQuery 1.6 you should be using `.prop('selectedIndex', 0);` regardless of if `.attr()` works or not :) – gnarf Aug 11 '11 at 13:59
  • 1
    Correct, it in fact might not work in 1.7. see accepted answer : http://stackoverflow.com/questions/8010664/jquery-1-7-this-attrtype-for-select-gives-undefined-instaed-of-select-on – 4imble Nov 21 '11 at 17:05
  • +1 for the addendum. My old code got broken due to this issue – BiLaL Apr 19 '14 at 10:54
  • Website I'm working is using jQuery v3.3.1 and `.attr()` did not work; using `.prop()` did though. Thanks bois – clamum May 24 '22 at 15:59
13

I'm writing this answer in 2015, and for some reason (probably older versions of jQuery) none of the other answers have worked for me. I mean, they change the selected index, but it doesn't actually reflect on the actual dropdown.

Here is another way to change the index, and actually have it reflect in the dropdown:

$('#mydropdown').val('first').change();
PaulG
  • 6,920
  • 12
  • 54
  • 98
  • 2
    Thanks for your answer. Only this answer is worked for me – Viraj Dhamal Sep 11 '15 at 11:15
  • Also in 2015, I have no problem with `prop('selectedIndex', ...);` (tested with Chrome & Firefox) changing the selection. – Lambart Sep 22 '15 at 23:15
  • 2
    For what it's worth, it should be pointed out that you're doing different here is triggering a `change` event on the drop-down, which could also be a useful fix/workaround for people who are changing the selection by calling `prop('selectedIndex', ...)`, rather than `val(...)`. Perhaps the problem was that you're listening for a `change` event, and THAT's what wasn't working for you? It's true that simply changing the `prop`erty is not going to fire any events... – Lambart Sep 22 '15 at 23:20
10

JQuery code:

$("#sel_status").prop('selectedIndex',1);

Jsp Code:

Status:
<select name="sel_status"
    id="sel_status">
    <option value="1">-Status-</option>
    <option>ALL</option>
    <option>SENT</option>
    <option>RECEIVED</option>
    <option>DEACTIVE</option>
</select>
Joe M
  • 3,060
  • 3
  • 40
  • 63
sathya
  • 1,404
  • 2
  • 15
  • 26
9

I'm using

$('#elem').val('xyz');

to select the option element that has value='xyz'

Praveen
  • 55,303
  • 33
  • 133
  • 164
djs
  • 111
  • 1
  • 2
4

You want to grab the value of the first option in the select element.

$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
MacAnthony
  • 4,471
  • 2
  • 23
  • 26
4

To select the 2nd option

$('#your-select-box-id :nth-child(2)').prop('selected', true);

Here we add the `trigger('change') to make the event fire.

$('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');
Jarrod
  • 9,349
  • 5
  • 58
  • 73
3

This also work proper in chrome and internet Explorer

$("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();

Put according your choice possition value of DropDown 0,1,2,3,4.....

1
$("[id$='" + originalId + "']").val("0 index value");

will set it to 0

Josh Mein
  • 28,107
  • 15
  • 76
  • 87
  • Not sure if this is just old but does not work Jan 2022 – Rafa Guillermo Jan 11 '22 at 14:31
  • @Ihopethisishelpfultoyou I was referring to something similar to MacAnthonys response. You are not meant to include the actual text of `0 index value` but the value of the option that is the 0 index. His answer dynamically pulls the value of the option at the 0 index so would result in the same thing except his would work in any scenario due to not having to hardcode the value. – Josh Mein Jan 12 '22 at 17:27
1

Select 4th option

$('#select').val($('#select option').eq(3).val());

example on jsfiddle

dabar
  • 61
  • 1
  • 2
0

This will work:

<head>
    <script type="text/javascript">
        function Init () {
            var counter = document.getElementById ("counter");
            for (var i = 1; i < 1000; i++) {
                var option = new Option (i, i);
                counter.options.add (option);
            }
            counter.focus ();
        }
        
        function OnKeyPressCounter (event, counter) {
            var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
        
            if (chCode == 68 /* + */) {
                if (counter.selectedIndex < counter.options.length - 1) {
                    counter.selectedIndex++;
                }
            }
            if (chCode == 45 /* - */) {
                if (counter.selectedIndex > 0) {
                    counter.selectedIndex--;
                }
            }
        }
    </script>
</head>
<body onload="Init ()">
    Use the + and - keys to increase/decrease the counter.
    <select id="counter" onkeypress="OnKeyPressCounter(event, this)" style="width:80px"></select>
</body>
Merrin K
  • 1,602
  • 1
  • 16
  • 27