271

I have an select box:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

I'd like to set one of the options as "selected" based on it's selected index.

For example, if I am trying to set "Number 3", I'm trying this:

$('#selectBox')[3].attr('selected', 'selected');

But this doesn't work. How can I set an option as selected based on it's index using jQuery?

Thanks!

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    This is almost exactly the same as you previous question: http://stackoverflow.com/questions/1280369/jquery-set-selected-option-using-next – Kobi Aug 14 '09 at 22:41
  • Possible duplicate of [jQuery - setting the selected value of a select control via its text description](http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) – Organic Advocate Sep 19 '16 at 17:57

25 Answers25

470

NOTE: answer is dependent upon jQuery 1.6.1+

$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true);  // To select via value

Thanks for the comment, .get won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq function can be used outside of the selector as well if you prefer.

$('#selectBox option').eq(3).prop('selected', true);

You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:

$("#selectBox").val("3");

Note: .val(3) works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option> requires you to use .val("hello"))

Marc
  • 9,254
  • 2
  • 29
  • 31
  • 7
    +1 - The second option worked for me. The chosen answer by John Kugelman did not work for me in IE7. – P.Brian.Mackey Jun 27 '11 at 17:44
  • 2
    Sadly, none of these ways fire a change() event for me. I have $('#selectBox').change(function() { alert('changed') }); – mike jones Sep 26 '11 at 17:44
  • 31
    @mikejones - that's by design. When you're programmatically setting a selected option, you may not always want the bound change event to be triggered (like on a page load event.) To solve that jquery leaves it up to the developer to decide. In your case you can simply call $('#selectBox').change(); after you have called $('#selectBox').val("3"); – Marcus Pope Sep 29 '11 at 18:54
  • 1
    Thanks for the comment, Marcus. Glad to know its not a bug. – mike jones Sep 29 '11 at 19:18
  • 1
    +1 $('#selectBox option').eq(3).attr('selected', 'selected'); works excellent! – Devner Feb 26 '12 at 13:26
  • 1
    The 3rd option was simple and effective – MrM May 18 '12 at 15:22
  • 2
    Is the first option 0 or 1? – Lee Meador May 01 '13 at 20:55
  • 1
    @LeeMeador If I understand your question, the first option is `0` when using `eq(index)`. When you use `nth-child(index)` *there are other uses such as `even`, `odd`, etc*, you start with the index `1`. – Marc May 02 '13 at 14:34
  • 3
    I thought it worth mentioning that post-jQuery 1.6.1, the recommended method for modifying boolean properties of an element is `.prop()` rather than `.attr()`. – DevlshOne Jul 01 '13 at 15:19
  • @DevlshOne absolutely right, forgot all about this question. Updated to show `.prop` since `.attr` doesn't always work post 1.9.1 anyway. Modifying the property is the correct usage anyway (whether pojs or jquery) – Marc Jul 02 '13 at 21:20
  • Using jQuery Mobile don't forget to update the UI so your selection displays. $('#select').selectmenu().selectmenu('refresh'); – Olmstov Feb 01 '18 at 17:58
  • As noted earlier, the nth-child selectors are "1-indexed" rather than the typical 0 index. So to select the first list item, use :nth-child(1). See https://api.jquery.com/nth-child-selector/. – Ken Palmer Apr 04 '18 at 15:24
118

This may also be useful, so I thought I'd add it here.

If you would like to select a value based on the item's value and not the index of that item then you can do the following:

Your select list:

<select id="selectBox">
    <option value="A">Number 0</option>
    <option value="B">Number 1</option>
    <option value="C">Number 2</option>
    <option value="D">Number 3</option>
    <option value="E">Number 4</option>
    <option value="F">Number 5</option>
    <option value="G">Number 6</option>
    <option value="H">Number 7</option>
</select>

The jquery:

$('#selectBox option[value=C]').attr('selected', 'selected');

$('#selectBox option[value=C]').prop('selected', true);

The selected item would be "Number 2" now.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
dnoxs
  • 1,541
  • 2
  • 11
  • 17
  • note: there's an extra underscore after the $()... otherwise, this works fantastically – Dusty J Oct 10 '10 at 07:49
  • 1
    +1 I couldn't get this to work exactly, but from this I finally got it to work with this following syntax: $("#selectBox option[value='C']")[0].selected = true; – Wes Grant Jun 10 '11 at 02:59
  • 5
    Just be aware that `.attr('selected', 'selected')` should not be used several times on the same select, as some browsers can get confused (in some cases they start marking several items in the dom as `selected=selected"`. If you need to change the selected value more often (e.g. on a button click) use `.prop('selected', true)` as suggested by Marc. - Is just had a lot pain - and wasted time - because of this issue! – Tom Fink Aug 20 '13 at 14:16
  • This $('#selectBox option[value=C]').prop('selected', true); worked like a charm. – Winter MC Jul 06 '21 at 10:09
68

Try this instead:

$("#selectBox").val(3);
Chris Brandsma
  • 11,666
  • 5
  • 47
  • 58
53

Even simpler:

$('#selectBox option')[3].selected = true;
sean
  • 531
  • 4
  • 2
  • 1
    This worked for me, I also needed to select by INDEX not VALUE. – Alan May 01 '12 at 21:51
  • 2
    This answer gave me what i needed.. I was missing the 'option' part of the selector when trying to select by name $('select[name="select_name"] option)[index].selected=true; – Smith Smithy Aug 09 '13 at 04:16
17
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

# Set element by text
$("#select").val("option Text").attr("selected", "selected");

when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected'); for remove previous selects .

# Set element by value
$("#select").val("2");

# Get selected text
$("#select").children("option:selected").text();  # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes 

# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();

# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));

# Select First Option
$("#select option:first");

# Select Last Item
$("#select option:last").remove();


# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");

# Remove an item
$("#select option:eq(0)").remove();
M Rostami
  • 4,035
  • 1
  • 35
  • 39
  • +1 for : $('#select option').removeAttr('selected'); simplest option to return 'selected' item to top, or no defined selection. – Michahell Jun 29 '15 at 16:44
11

What's important to understand is that val() for a select element returns the value of the selected option, but not the number of element as does selectedIndex in javascript.

To select the option with value="7" you can simply use:

$('#selectBox').val(7); //this will select the option with value 7.

To deselect the option use an empty array:

$('#selectBox').val([]); //this is the best way to deselect the options

And of course you can select multiple options*:

$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7

*However to select multiple options, your <select> element must have a MULTIPLE attribute, otherwise it won't work.

Anonymous
  • 4,692
  • 8
  • 61
  • 91
11

I've always had issues with prop('selected'), the following has always worked for me:

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');
hellojebus
  • 3,267
  • 1
  • 21
  • 23
8

Try this:

$('select#mySelect').prop('selectedIndex', optionIndex);

Eventually, trigger a .change event :

$('select#mySelect').prop('selectedIndex', optionIndex).change();
NicolasBernier
  • 1,586
  • 14
  • 15
6

Hope this could help Too

$('#selectBox option[value="3"]').attr('selected', true);
Harry
  • 87,580
  • 25
  • 202
  • 214
Andoy Abarquez
  • 1,119
  • 4
  • 17
  • 30
5

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

dabar
  • 61
  • 1
  • 2
4

The pure javascript selectedIndex attribute is the right way to go because,it's pure javascript and works cross-browser:

$('#selectBox')[0].selectedIndex=4;

Here is a jsfiddle demo with two dropdowns using one to set the other:

<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
</select>

You can also call this before changing the selectedIndex if what you want is the "selected" attribute on the option tag (here is the fiddle):

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');
jacmkno
  • 1,189
  • 11
  • 25
4

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."

slh777
  • 105
  • 2
  • 5
4

In 1.4.4 you get an error: $("#selectBox option")[3].attr is not a function

This works: $('#name option:eq(idx)').attr('selected', true);

Where #name is select id and idx is the option value you want selected.

pjumble
  • 16,880
  • 6
  • 43
  • 51
4

I often use trigger ('change') to make it work

$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');

Example with id select = selectA1 and position_index = 0 (frist option in select):

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
Ly Thanh Ngo
  • 394
  • 1
  • 2
  • 15
4

To clarify Marc's and John Kugelman's answers, you could use:

$('#selectBox option').eq(3).attr('selected', 'selected')

get() will not work if used in the way specified because it gets the DOM object, not a jQuery object, so the following solution will not work:

$('#selectBox option').get(3).attr('selected', 'selected')

eq() gets filters the jQuery set to that of the element with the specified index. It's clearer than $($('#selectBox option').get(3)). It's not all that efficient. $($('#selectBox option')[3]) is more efficient (see test case).

You don't actually need the jQuery object though. This will do the trick:

$('#selectBox option')[3].selected = true;

http://api.jquery.com/get/

http://api.jquery.com/eq/

One other vitally important point:

The attribute "selected" is not how you specify a selected radio button (in Firefox and Chrome at least). Use the "checked" attribute:

$('#selectBox option')[3].checked = true;

The same goes for check-boxes.

Community
  • 1
  • 1
Spycho
  • 7,698
  • 3
  • 34
  • 55
2
//funcion para seleccionar por el text del select
var text = '';
var canal = ($("#name_canal").val()).split(' ');
$('#id_empresa option').each(function(i, option) {
        text = $('#id_empresa option:eq('+i+')').text();
        if(text.toLowerCase() == canal[0].toLowerCase()){
            $('#id_empresa option:eq('+i+')').attr('selected', true);
        }
    });
andrwsv
  • 31
  • 1
1

Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:

$("#SelectList option").each(function () {
    if ($(this).val() == "1:00 PM")
        $(this).attr('selected', 'selected');
});

Also, if you have a dropdown (as opposed to a multi-select) you may want to do a break; so you don't get the first-value-found to be overwritten.

Nexxas
  • 883
  • 1
  • 8
  • 14
1

I faced same problem. First you need go through the events (i.e which event is happening first).

For example:

The First event is generating select box with options.

The Second event is selecting default option using any function such as val() etc.

You should ensure that the Second event should happen after the First event.

To achieve this take two functions lets say generateSelectbox() (for genrating select box) and selectDefaultOption()

You need to ensure that selectDefaultOption() should be called only after the execution of generateSelectbox()

Mani
  • 11
  • 1
1

You can also init multiple values if your selectbox is a multipl:

$('#selectBox').val(['A', 'B', 'C']);
Harry
  • 87,580
  • 25
  • 202
  • 214
1
$('#selectBox option').get(3).attr('selected', 'selected')

When using the above I kept getting errors in webkit (Chrome) saying:

"Uncaught TypeError: Object # has no method 'attr'"

This syntax stops those errors.

$($('#selectBox  option').get(3)).attr('selected', 'selected');
benembery
  • 666
  • 7
  • 20
1

If you just want to select an item based of a particular property of an item then jQuery option of type[prop=val] will get that item. Now I don't care about the index I just wanted the item by its value.

$('#mySelect options[value=3]).attr('selected', 'selected');
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
codeguy
  • 11
  • 1
1

I need a solution that has no hard coded values in the js file; using selectedIndex. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)

$("#selectBox").get(0).selectedIndex = 1; 
Alfred
  • 21,058
  • 61
  • 167
  • 249
Jean-Marc
  • 11
  • 1
0

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

0

After spending too much time, this one worked for me.

$("#selectbox")[0].selectedIndex = 1;
linktoahref
  • 7,812
  • 3
  • 29
  • 51
Pravin L
  • 31
  • 1
  • 5
-2

Shortly:

$("#selectBox").attr("selectedIndex",index)

where index is the selected index as integer.

Csaba
  • 1
  • 1