How To Add Options To A Select Element Using Jquery?

The finest example using HTML, and jQuery is what I’ve presented. Therefore, you can learn how to add new select options using jQuery. Simple explanations are provided for each stage.

 

  1. Create a HTML Code:
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <p>
      Select one of the proposed options:
      <select id="mySelect">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
      </select>
    </p>
  </body>
</html>

 

2. Create JavaScript Code:

<script type="text/javascript">    
      jQuery(document).ready(function () {
        var optionText = 'Option 3';
        var optionValue = 'option3';
       jQuery('#mySelect').append(jQuery('<option>').val(optionValue).text(optionText));
      });
</script>

This code creates a new option element with a value of “option3” and text of “Option 3”, and then appends it to the select element with the ID of “mySelect”. You can add more options in a similar way by calling the append() method again with a new option element.

 

Output:

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories