Asked 3 years ago
29 Jun 2021
Views 278
Kali

Kali posted

Set selected option of select box

Set selected option of select box
rajiv

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>
  // Get a reference to the select element
  var selectElement = document.getElementById('my-select');
  
  // Set the selected index to 1 (i.e., select the second option)
  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>
  // Set the selected index to 1 (i.e., select the second option)
  $('#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.
Post Answer