How To Add First Options To A Select Element Using JQuery

You can add the first option to a select element using jQuery by using the prepend() method to add a new option element to the beginning of the select element’s options.

  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';
        var optionValue = 'option';
       jQuery('#mySelect').prepend(jQuery('<option>').val(optionValue).text(optionText));
      });
</script>

In this example, mySelect is the ID of the select element to which you want to add the first option. The prepend() method is used to add a new option.

 

Output:

Submit a Comment

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

Subscribe

Select Categories