Languages
[Edit]
EN

JavaScript - how to add options (items) to select (ComboBox) element

3 points
Created by:
Root-ssh
6407

In this article, we're going to have a look at how to add new options (items) to select (ComboBox) element in JavaScript. Solutions for this problems can be divided into 2 groups:

  • that use option element API (example 1 and 2),
  • that use DOM element API (example 3¬†and 4).

Look on below examples to see how they work:

1. add method example

Approach presented in this section uses add method available for each select element.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <select id="fruits"></select>
  <script>

    var fruits = document.querySelector('#fruits');

    var orange = document.createElement('option');
    orange.text = 'Orange';
    orange.value = 'orange';
    fruits.add(orange);

    var apple = document.createElement('option');
    apple.text = 'Apple';
    apple.value = 'apple';
    fruits.add(apple);

  </script>
</body>
</html>

2. options property with add method example

In this section we use options property that keeps all items in select element.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <select id="fruits"></select>
  <script>

    var fruits = document.querySelector('#fruits');

    var orange = document.createElement('option');
    orange.text = 'Orange';
    orange.value = 'orange';
    fruits.options.add(orange);

    var apple = document.createElement('option');
    apple.text = 'Apple';
    apple.value = 'apple';
    fruits.options.add(apple);

  </script>
</body>
</html>

3. appendChild method example

In this section we use appendChild method that append child elements to select element - used typical DOM method.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <select id="fruits"></select>
  <script>

    var fruits = document.querySelector('#fruits');

    var orange = document.createElement('option');
    orange.text = 'Orange';
    orange.value = 'orange';
    fruits.appendChild(orange);

    var apple = document.createElement('option');
    apple.text = 'Apple';
    apple.value = 'apple';
    fruits.appendChild(apple);

  </script>
</body>
</html>

4. innerHTML property example

In this section we use innerHTML property that in presented case overrides select element content - used typical DOM proeprty.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <select id="fruits"></select>
  <script>

    var fruits = document.querySelector('#fruits');

    fruits.innerHTML = '' + 
      '<option value="orange">Orange</option>' +
      '<option value="apple">Apple</option>';

  </script>
</body>
</html>

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.