Coder Perfect

How to use jQuery to select a dropdown option?

Problem

I’m wondering if it’s feasible to get jQuery to select an option in a dropdown box, say the fourth item?

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

I want the user to click a link, then have the value of the select> box alter as though the user picked it by selecting the option>.

Asked by dotty

Solution #1

How about

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

Example:

Instead of.attr, you should use.prop() in recent versions of jquery ()

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

Example:

Answered by Gabriele Petrioli

Solution #2

The solution:

$("#element-id").val('the value of the option');

Answered by Harold Sota

Solution #3

The selectedIndex property of HTML choose elements can be written to in order to select a specific option:

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

This may be done with plain JavaScript by:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;

Answered by Ja͢ck

Solution #4

This is how I would go about it.

 $("#idElement").val('optionValue').trigger('change');

Answered by franzisk

Solution #5

The val(value) function is the simplest method:

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

You don’t supply any parameters to acquire the desired value:

$('select').val();

You can also perform the following if you have the option value=”valueToSelect”>…/option>:

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

DEMO

Answered by Ionică Bizău

Post is based on https://stackoverflow.com/questions/4864620/how-to-use-jquery-to-select-a-dropdown-option