Open In App

How to add options to a drop-down list using jQuery?

Improve
Improve
Like Article
Like
Save
Share
Report

Given an HTML document with a drop-down list menu and our task is to add more options to the drop-down list using jQuery.

Approach : To add more option to the existing drop-down list using the append() method :

 var options = {
                val1: 'C#',
                val2: 'PHP'
            };
            var selectOption = $('#programmingLanguage');
            $.each(options, function (val, text) {
                selectOption.append(
                    $('<option></option>').val(val).html(text)
                );
            });

This is a small code snippet that can be used to add an option to an existing list and this code snippet is taken from a demonstration below where val1 and val2 have the option names, programmingLanguage is the id used for the select option, then by using the append() method the new options are merged with the existing list of options.

A detailed explanation of the append() method in JQuery can be found here .

Below is the code for the demonstration of the above approach.

HTML




<!DOCTYPE html>
<html>
  
<head>
    </script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Add an option to the dropdown list using jquery.</title>
</head>
  
<body>
    <h1 style="color: green;">GeeksForGeeks</h1>
      
<p>Programming Languages :</p>
  
    <select id='programmingLanguage'>
        <option value="Java" style="color: green; 
                font-weight: 700;">Java</option>
        <option value="Python" style="color: green; 
                font-weight: 700;">Python</option>
        <option value="CPP" style="color: green; 
                font-weight: 700;">CPP</option>
        <option value="C" style="color: green; 
                font-weight: 700;">C</option>
    </select>
      
<p> Click to add C# and PHP programming languages</p>
  
    <button onclick="addOption()">Add option</button>
    <!--Code to add an option to an existing set of option using jquery-->
    <script>
        function addOption() {
            var options = {
                val1: 'C#',
                val2: 'PHP'
            };
            var selectOption = $('#programmingLanguage');
            $.each(options, function (val, text) {
                selectOption.append(
                    $('<option></option>').val(val).html(text)
                );
            });
        }
    </script>
</body>
  
</html>


Output:



Last Updated : 22 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads