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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With