[jquery] jQuery Set Select Index

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!

This question is related to jquery jquery-selectors jquery-selectbox

The answer is


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

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

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.


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

Try this:

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

Eventually, trigger a .change event :

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

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.


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

Try this instead:

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

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

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>


select 3rd option

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

Example on jsfiddle


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


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

Hope this could help Too

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

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; 

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.


Even simpler:

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

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

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

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


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

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.


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


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.


Shortly:

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

where index is the selected index as integer.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to jquery-selectbox

How to check whether a select box is empty using JQuery/Javascript jQuery Set Select Index jQuery Set Selected Option Using Next Hide options in a select list using jQuery jQuery to retrieve and set selected option value of html select element Counting the number of option tags in a select tag in jQuery How can I select an element by name with jQuery? jQuery add blank option to top of list and make selected to existing dropdown jQuery: Selecting by class and input type Selecting option by text content with jQuery