rajiv
answered Apr 28 '23 00:00
To set the selected option of a select box, you can use JavaScript or jQuery to modify the selectedIndex property of the select element.
Here's an example using plain JavaScript:
<select id="my-select">
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
<option value="option-3">Option 3</option>
</select>
<script>
var selectElement = document.getElementById('my-select');
selectElement.selectedIndex = 1;
</script>
And here's the same example using jQuery:
<select id="my-select">
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
<option value="option-3">Option 3</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#my-select').prop('selectedIndex', 1);
</script
>
In both examples, we first get a reference to the select element using document.getElementById or $('#my-select') . Then we set the selectedIndex property of the select element to the index of the option we want to select (in this case, 1, which corresponds to the second option).
Note that you can customize this approach to fit your specific use case.