How to use jQuery to select a dropdown option?

I was wondering if it’s possible to get jQuery to select an <option>, say the 4th item, in a dropdown box?

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

I want the user to click a link, then have the <select> box change its value, as if the user has selected it by clicking on the <option>.


Solution 1:

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>

Solution 2:

The solution:

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