In this example, we have a drop-down list with the id and a button with the id When the button is clicked, we use jQuery to remove the selected attribute from all options, and then we set the second option as selected by adding the selected attribute to it. Note that we use the () method to remove the selected attribute, and the attr() method to add it back.", "dateCreated": "2023-04-28 00:00:00", "upvoteCount": 0, "url": "https://www.arrayoverflow.com/question/set-an-option-value-as-selected/1029#2143", "author": { "@type": "Person", "name": "ravi" } } ] } }
Asked 3 years ago
29 Jun 2021
Views 226
Dina

Dina posted

Set an option value as selected

Set an option value as selected
ravi

ravi
answered Apr 28 '23 00:00

To set an option value as selected, you can use the selected attribute on the option element. Here's an example:



<select id="my-select">
  <option value="option1">Option 1</option>
  <option value="option2" selected>Option 2</option>
  <option value="option3">Option 3</option>
</select>

In this example, the second option element has the selected attribute, which means it will be selected by default when the page loads. If you want to set a different option as selected dynamically, you can use jQuery to add or remove the selected attribute. Here's an example:



<select id="my-select">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
</select>

<button id="change-btn">Change selection</button>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function() {
    $('#change-btn').click(function() {
      // Remove the selected attribute from all options
      $('#my-select option').removeAttr('selected');
      // Set the second option as selected
      $('#my-select option:nth-child(2)').attr('selected', true);
    });
  });

</script>
In this example, we have a drop-down list with the id my-select, and a button with the id change-btn. When the button is clicked, we use jQuery to remove the selected attribute from all options, and then we set the second option as selected by adding the selected attribute to it. Note that we use the removeAttr () method to remove the selected attribute, and the attr() method to add it back.
Post Answer