Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery to select a dropdown option?

People also ask

How do I select a Dropdownlist using jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do I add options to a Dropdownlist using jQuery?

Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.

How do I select a dropdown option?

A dropdown is represented by <select> tag and the options are represented by <option> tag. To select an option with its value we have to use the selectByValue method and pass the value attribute of the option that we want to select as a parameter to that method.


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>

The solution:

$("#element-id").val('the value of the 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;

I would do it this way

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