176

I was wondering if it’s possible to get jQuery to select an <option>, say the 4th item, in a dropdown box?

<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>

I want the user to click a link, then have the <select> box change its value, as if the user has selected it by clicking on the <option>.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
dotty
  • 40,405
  • 66
  • 150
  • 195

14 Answers14

199

How about

$('select>option:eq(3)').attr('selected', true);

Example:

$('select>option:eq(3)').attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>

for modern versions of jquery you should use the .prop() instead of .attr()

$('select>option:eq(3)').prop('selected', true);

Example:

$('select>option:eq(3)').prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
</select>
Erfan Bahramali
  • 392
  • 3
  • 13
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • 4
    imo this shouldn't even work; the selected state of an option should be triggered by changing the state of the select itself instead :) – Ja͢ck Jan 17 '13 at 14:28
  • 1
    `selectElement.selectedIndex = index;` is what Jack means. – rlemon Jan 31 '13 at 18:11
  • @rlemon, i understand, but `selectedIndex` cannot be used for multiple selection when `multiple` attribute is used. And the normal (*html*) way to set selected elements is the `selected` attribute of the `option` elements. – Gabriele Petrioli Jan 31 '13 at 18:32
  • @GabyakaG.Petrioli The normal way is actually to set the `selected` property of each corresponding `options` element to `true` (and optionally the rest to `false` explicitly). Multiple selections are pretty nasty actually :) – Ja͢ck Jan 31 '13 at 18:59
  • (*i think that is what i said, too*) – Gabriele Petrioli Jan 31 '13 at 19:38
  • There's a subtle difference, though that said, your current answer doesn't deal with multiple either. – Ja͢ck Jan 31 '13 at 23:37
  • @jack, it does not as the OP does not need it. I was responding to your comment that "*imo this shouldn't even work; the selected state of an option should be triggered by changing the state of the select itself instead*" and i am saying that this concept could not deal with all valid usages of a select element. (*if you are arguing on the W3C specs, then that is another issue, and glad to discuss it on the W3C mailing lists*) – Gabriele Petrioli Feb 01 '13 at 00:55
  • Sorry for that, I should remind myself not to write foot-in-mouth comments when I'm still sleeping :( I didn't realize that `new Option() instanceof Node`, so assuming `.attr('selected')` maps to the property, it be kosher; of course, the argument for using `.selectedIndex` still holds for regular dropdowns :) – Ja͢ck Feb 01 '13 at 02:25
  • The problem is that it doesn't fire an 'onchange' event. – Guy Korland May 12 '13 at 08:12
  • It is not triggering 'onchange' event. Any hacks for that too?? – sundeepg Jun 14 '16 at 08:15
  • 6
    @sunnyiitkgp the `onchange` event is never triggered when the value is changed programmatically. You could add a `.trigger('change')` at the end to also fire the event (*although it will fire regardless of the value having actually changed*) – Gabriele Petrioli Jun 14 '16 at 18:43
  • I ran into an issue where the dropdown value wouldn't "visually" change until I performed a .change() on the target. However, since I had an event tied to the dropdown, it would cause the event to also trigger. Using .prop('selected', true) solved the issue! – Jarrett Barnett Apr 16 '17 at 05:21
163

The solution:

$("#element-id").val('the value of the option');
Charlie
  • 8,530
  • 2
  • 55
  • 53
Harold Sota
  • 7,490
  • 12
  • 58
  • 84
56

HTML select elements have a selectedIndex property that can be written to in order to select a particular option:

$('select').prop('selectedIndex', 3); // select 4th option

Using plain JavaScript this can be achieved by:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 3
    The problem is that it doesn't fire an 'onchange' event. – Guy Korland May 12 '13 at 08:02
  • 3
    @GuyKorland This happens with none of the other answers either, demonstrated [here](http://jsbin.com/ehahug/1/); if you want an event to fire, you have to do it manually. – Ja͢ck May 12 '13 at 13:17
  • 1
    @Jack Is there a short way? The only way I found: var fireEvent = function(selectElement){ if(selectElement){ if ("fireEvent" in selectElement){ selectElement.fireEvent("onchange"); } else { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); selectElement.dispatchEvent(evt); } } } – Guy Korland May 12 '13 at 20:48
  • 5
    @GuyKorland jQuery exposes `.trigger()` for that, but since you're already doing this with code it would be easy to also call the change handlers yourself. – Ja͢ck May 13 '13 at 02:11
40

I would do it this way

 $("#idElement").val('optionValue').trigger('change');
Francesco Gasparetto
  • 1,819
  • 16
  • 20
26

The easiest way is val(value) function:

$('select').val(2);

And to get the selected value you give no arguments:

$('select').val();

Also, you if you have <option value="valueToSelect">...</option>, you can do:

$('select').val("valueToSelect");

DEMO

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
25

if your options have a value, you can do this:

$('select').val("the-value-of-the-option-you-want-to-select");

'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

Victor
  • 4,721
  • 1
  • 26
  • 31
11

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);
nlareu
  • 125
  • 1
  • 10
6
 Try with the below codes. All should work. 
    $('select').val(2);
    $('select').prop('selectedIndex', 1);
    $('select>option[value="5"]').prop('selected', true);
    $('select>option:eq(3)').attr('selected', 'selected');
    $("select option:contains(COMMERCIAL)").attr('selected', true);
Mamunur Rashid
  • 281
  • 4
  • 6
3
 $('select>option:eq(3)').attr('selected', 'selected');

One caveat here is if you have javascript watching for select/option's change event you need to add .trigger('change') so the code become.

 $('select>option:eq(3)').attr('selected', 'selected').trigger('change');

because only calling .attr('selected', 'selected') does not trigger the event

kanitw
  • 874
  • 10
  • 19
3

With '' element usually we use 'value' attribute. It will make it easier to set then:

$('select').val('option-value');
Savaratkar
  • 1,974
  • 1
  • 24
  • 44
3

Try this:

$('#mySelectElement option')[0].selected = true;

Regards!

Nicolas Finelli
  • 2,170
  • 1
  • 14
  • 9
3

I prefer nth-child() to eq() as it uses 1-based indexing rather than 0-based, which is slightly easier on my brain.

//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);
Lee D
  • 12,551
  • 8
  • 32
  • 34
  • The "1-based index" is better when manipulating things with dates. Saves me from a lot of troubles. thanks. – TCB13 Feb 01 '12 at 22:24
2

answer with id:

$('#selectBoxId').find('option:eq(0)').attr('selected', true);
Javad Masoumi
  • 347
  • 2
  • 5
0

This works for me:

$selectedindex=4

If you want to randomise options, you could always do something like this:

$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)

Whilst the 2nd lies outside scope of your questions, it serves to illustrate how 1st could be applied / amended as req.

JB-007
  • 2,156
  • 1
  • 6
  • 22
  • (note - $0 serves to represent $, but I'm relatively new to Python so still familarising myself with differences in relation to some of this syntax - but selectedindex still avail. in jquery world - hope this helps. – JB-007 Oct 03 '20 at 22:53