How to use jQuery to select a dropdown option?
HTML select elements have a selectedIndex
property that can be written to in order to select a particular option:
$('select').prop('selectedIndex', 3); // select 4th option
Using plain JavaScript this can be achieved by:
// use first select element
var el = document.getElementsByTagName('select')[0];
// assuming el is not null, select 4th option
el.selectedIndex = 3;
The solution:
$("#element-id").val('the value of the option');
How about
$('select>option:eq(3)').attr('selected', true);
Example:
$('select>option:eq(3)').attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
for modern versions of jquery you should use the .prop()
instead of .attr()
$('select>option:eq(3)').prop('selected', true);
Example:
$('select>option:eq(3)').prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>