jQuery Set Select Index

JqueryJquery Selectors

Jquery Problem Overview


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!

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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.

Solution 3 - Jquery

Try this instead:

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

Solution 4 - Jquery

Even simpler:

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

Solution 5 - Jquery

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

 
 

Solution 6 - Jquery

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.

Solution 7 - Jquery

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

Solution 8 - Jquery

Try this:

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

Eventually, trigger a .change event :

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

Solution 9 - Jquery

Hope this could help Too

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

Solution 10 - Jquery

select 3rd option

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

Example on jsfiddle

Solution 11 - Jquery

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

Solution 12 - Jquery

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.

Solution 13 - Jquery

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.

Solution 14 - Jquery

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

Solution 15 - Jquery

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

Solution 16 - Jquery

//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);
		}
	});

Solution 17 - Jquery

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

Solution 18 - Jquery

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

Solution 19 - Jquery

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; 

Solution 20 - Jquery

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.

Solution 21 - Jquery

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

Solution 22 - Jquery

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

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

Solution 23 - Jquery

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>

Solution 24 - Jquery

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

$("#selectbox")[0].selectedIndex = 1;

Solution 25 - Jquery

Shortly:

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

where index is the selected index as integer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDodinasView Question on Stackoverflow
Solution 1 - JqueryMarcView Answer on Stackoverflow
Solution 2 - JquerydnoxsView Answer on Stackoverflow
Solution 3 - JqueryChris BrandsmaView Answer on Stackoverflow
Solution 4 - JqueryseanView Answer on Stackoverflow
Solution 5 - JqueryM RostamiView Answer on Stackoverflow
Solution 6 - JqueryAnonymousView Answer on Stackoverflow
Solution 7 - JqueryhellojebusView Answer on Stackoverflow
Solution 8 - JqueryNicolasBernierView Answer on Stackoverflow
Solution 9 - JqueryAndoy AbarquezView Answer on Stackoverflow
Solution 10 - JquerydabarView Answer on Stackoverflow
Solution 11 - Jqueryslh777View Answer on Stackoverflow
Solution 12 - JqueryMicah FletcherView Answer on Stackoverflow
Solution 13 - JquerySpychoView Answer on Stackoverflow
Solution 14 - JqueryjacmknoView Answer on Stackoverflow
Solution 15 - JqueryLy Thanh NgoView Answer on Stackoverflow
Solution 16 - JqueryandrwsvView Answer on Stackoverflow
Solution 17 - JquerybenemberyView Answer on Stackoverflow
Solution 18 - JquerycodeguyView Answer on Stackoverflow
Solution 19 - JqueryJean-MarcView Answer on Stackoverflow
Solution 20 - JqueryNexxasView Answer on Stackoverflow
Solution 21 - JqueryManiView Answer on Stackoverflow
Solution 22 - JqueryFrank GlückView Answer on Stackoverflow
Solution 23 - JqueryRam Lakhan YadavView Answer on Stackoverflow
Solution 24 - JqueryPravin LView Answer on Stackoverflow
Solution 25 - JqueryCsabaView Answer on Stackoverflow