EN
JavaScript - how to add options (items) to select (ComboBox) element
3 points
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:
Approach presented in this section uses add
method available for each select
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<select id="fruits"></select>
5
<script>
6
7
var fruits = document.querySelector('#fruits');
8
9
var orange = document.createElement('option');
10
orange.text = 'Orange';
11
orange.value = 'orange';
12
fruits.add(orange);
13
14
var apple = document.createElement('option');
15
apple.text = 'Apple';
16
apple.value = 'apple';
17
fruits.add(apple);
18
19
</script>
20
</body>
21
</html>
In this section we use options
property that keeps all items in select
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<select id="fruits"></select>
5
<script>
6
7
var fruits = document.querySelector('#fruits');
8
9
var orange = document.createElement('option');
10
orange.text = 'Orange';
11
orange.value = 'orange';
12
fruits.options.add(orange);
13
14
var apple = document.createElement('option');
15
apple.text = 'Apple';
16
apple.value = 'apple';
17
fruits.options.add(apple);
18
19
</script>
20
</body>
21
</html>
In this section we use appendChild
method that append child elements to select
element - used typical DOM method.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<select id="fruits"></select>
5
<script>
6
7
var fruits = document.querySelector('#fruits');
8
9
var orange = document.createElement('option');
10
orange.text = 'Orange';
11
orange.value = 'orange';
12
fruits.appendChild(orange);
13
14
var apple = document.createElement('option');
15
apple.text = 'Apple';
16
apple.value = 'apple';
17
fruits.appendChild(apple);
18
19
</script>
20
</body>
21
</html>
In this section we use innerHTML
property that in presented case overrides select
element content - used typical DOM proeprty.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<select id="fruits"></select>
5
<script>
6
7
var fruits = document.querySelector('#fruits');
8
9
fruits.innerHTML = '' +
10
'<option value="orange">Orange</option>' +
11
'<option value="apple">Apple</option>';
12
13
</script>
14
</body>
15
</html>