272

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!

2

25 Answers 25

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"))

12
  • 7
    +1 - The second option worked for me. The chosen answer by John Kugelman did not work for me in IE7. Commented Jun 27, 2011 at 17:44
  • 2
    Sadly, none of these ways fire a change() event for me. I have $('#selectBox').change(function() { alert('changed') });
    – mike jones
    Commented Sep 26, 2011 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"); Commented Sep 29, 2011 at 18:54
  • 2
    Is the first option 0 or 1?
    – Lee Meador
    Commented May 1, 2013 at 20:55
  • 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
    Commented Jul 1, 2013 at 15:19
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.

4
  • note: there's an extra underscore after the $()... otherwise, this works fantastically
    – Dusty J
    Commented Oct 10, 2010 at 7: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;
    – Jen Grant
    Commented Jun 10, 2011 at 2: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
    Commented Aug 20, 2013 at 14:16
  • This $('#selectBox option[value=C]').prop('selected', true); worked like a charm.
    – Winter MC
    Commented Jul 6, 2021 at 10:09
68

Try this instead:

$("#selectBox").val(3);
6
  • 2
    This makes copying from one element to another dead simple as well!
    – Sonny
    Commented Dec 7, 2010 at 18:42
  • typo: after "selectBox you're missing a quote
    – Niels Bom
    Commented Dec 21, 2010 at 16:29
  • 1
    This is simple and straightforward. I much prefer this solution. Commented May 23, 2011 at 20:41
  • This works in Chrome, but doesn't work for me with IE9. I use: $('#selectBox option')[3].selected = true; (seans answer).
    – cederlof
    Commented Sep 26, 2012 at 7:27
  • FWIW, This doesn't even work in Chrome for me. Using the ":nth-child" answer worked for me.
    – Jay Taylor
    Commented Oct 24, 2012 at 21:42
53

Even simpler:

$('#selectBox option')[3].selected = true;
2
  • 1
    This worked for me, I also needed to select by INDEX not VALUE.
    – Alan
    Commented May 1, 2012 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; Commented Aug 9, 2013 at 4: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();
1
  • +1 for : $('#select option').removeAttr('selected'); simplest option to return 'selected' item to top, or no defined selection.
    – Michahell
    Commented Jun 29, 2015 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.

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');
8

Try this:

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

Eventually, trigger a .change event :

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

Hope this could help Too

$('#selectBox option[value="3"]').attr('selected', true);
5

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');
5

select 3rd option

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

Example on jsfiddle

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

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.

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.

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');
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);
        }
    });
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');
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.

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; 
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');
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()

1

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

$('#selectBox').val(['A', 'B', 'C']);
1

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

$("#selectbox")[0].selectedIndex = 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>

-2

Shortly:

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

where index is the selected index as integer.

1
  • this code works $('#selectBox').prop({selectedIndex:desiredIndex})
    – jurijcz
    Commented Aug 7, 2014 at 13:02