- How to Add Options to a Select Element using jQuery
- The append() Method
- JavaScript: Dynamically Add & Remove Options
- Adding options
- 1) Using the Option constructor and add() method
- 2) Using the DOM methods
- Removing Options
- Put it all together
- Summary
- Select options Collection
- Description
- Browser Support
- Syntax
- Properties
- Methods
- Technical Details
- More Examples
- Example
- Example
- Example
- Example
- Example
- Example
- Example
- Example
How to Add Options to a Select Element using jQuery
In this tutorial, we will find out the best method for adding options to a select element from a JavaScript object using jQuery. Let’s discuss each of the methods and try to solve the problem together.
The first method is appending the option tag to the select box. The option tag is created like an HTML string, and the select box is selected with the jQuery selector. The option is added with the append() method. This method inserts the specified content as the last child of the jQuery collection, thus adding the option to the select element.
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="selectId"> option value="firstEl">First Element option> option value="secondEl">Second Element option> select> p> button onclick="addOption()"> Add Element button> script type="text/javascript"> function addOption( ) < optText = 'New elemenet'; optValue = 'newElement'; $('#selectId').append(` `); > script> body> html>
The second method uses the Option() constructor for creating a new option. The Option() constructor is used to create a new option element. For creating a new option, the text and the value parameters are used. Then, the element is appended to the select box with the append() method:
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="selectId"> option value="firstEl">First Element option> option value="secondEl">Second Element option> select> p> button onclick="addOption()"> Add Element button> script type="text/javascript"> function addOption( ) < optText = 'New Element'; optValue = 'newElement'; $('#selectId').append(new Option(optText, optValue)); > script> body> html>
The third method is creating a new jQuery DOM element with the option tag. The value of the tag is specified with the val() method and the text with the text() method. Here, also you should use the append() method to add the element to the select box.
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="selectId"> option value="firstEl">First Element option> option value="secondEl">Second Element option> select> p> button onclick="addOption()"> Add Element button> script type="text/javascript"> function addOption( ) < optText = 'New element'; optValue = 'newElement'; $('#selectId') .append($('').val(optValue).text(optText)); > script> body> html>
The append() Method
The append() method inserts specified content at the end of the selected elements. The append() and appendTo() methods perform the same way. The difference between them is in the syntax-specifically, in the placement of the content and target. Use the prepend() method to insert the content at the beginning of the selected elements.
JavaScript: Dynamically Add & Remove Options
Summary: in this tutorial, you will learn how to dynamically add options to and remove options from a select element in JavaScript.
The HTMLSelectElement type represents the element. It has the add() method that dynamically adds an option to the element and the remove() method that removes an option from the element:
- add(option,existingOption) – adds a new element to the before an existing option.
- remove(index) – removes an option specified by the index from a .
Adding options
To add an option dynamically to a element, you use these steps:
There are multiple ways to create an option dynamically and add it to a in JavaScript.
1) Using the Option constructor and add() method
First, use the Option constructor to create a new option with the specified option text and value:
let newOption = new Option('Option Text','Option Value');
Code language: JavaScript (javascript)
Then, call the add() method of the HTMLSelectElement element:
const select = document.querySelector('select'); select.add(newOption,undefined);
Code language: JavaScript (javascript)
The add() method accepts two arguments. The first argument is the new option and the second one is an existing option.
In this example, we pass undefined in the second argument, the method add() method will add the new option to the end of the options list.
2) Using the DOM methods
First, construct a new option using DOM methods:
// create option using DOM const newOption = document.createElement('option'); const optionText = document.createTextNode('Option Text'); // set option text newOption.appendChild(optionText); // and option value newOption.setAttribute('value','Option Value');
Code language: JavaScript (javascript)
Second, add the new option to the select element using the appendChild() method:
const select = document.querySelector('select'); select.appendChild(newOption);
Code language: JavaScript (javascript)
Removing Options
There are also multiple ways to dynamically remove options from a select element.
The first way is to use the remove() method of the HTMLSelectElement type. The following illustrates how to remove the first option:
select.remove(0);
Code language: CSS (css)
The second way to remove an option is to reference the option by its index using the options collection and set its value to null :
select.options[0] = null;
Code language: JavaScript (javascript)
The third way is to use the removeChild() method and remove a specified option. The following code removes the first element of a the selectBox :
// remove the first element: select.removeChild(selectBox.options[0]);
Code language: JavaScript (javascript)
To remove all options of a select element, you use the following code:
function removeAll(selectBox) < while (selectBox.options.length > 0) < select.remove(0); > >
Code language: JavaScript (javascript)
When you remove the first option, the select element moves another option as the first option. The removeAll() function repeatedly removes the first option in the select element, therefore, it removes all the options.
Put it all together
We’ll build a application that allows users to add a new option from the value of an input text and remove one or more selected options.
Here’s the project’s structure:
├── css | └── style.css ├── js | └── app.js └── index.html
html>
html> head> title>JavaScript Selected Value title> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> link href="css/style.css" rel="stylesheet"> head> body> div id="container"> form> label for="framework">Framework: label> input type="text" id="framework" placeholder="Enter a framework" autocomplete="off"> button id="btnAdd">Add button> label for="list">Framework List: label> select id="list" name="list" multiple> select> button id="btnRemove">Remove Selected Framework button> form> div> script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)
const btnAdd = document.querySelector('#btnAdd'); const btnRemove = document.querySelector('#btnRemove'); const listbox = document.querySelector('#list'); const framework = document.querySelector('#framework'); btnAdd.onclick = (e) => < e.preventDefault(); // validate the option if (framework.value == '') < alert('Please enter the name.'); return; > // create a new option const option = new Option(framework.value, framework.value); // add it to the list listbox.add(option, undefined); // reset the value of the input framework.value = ''; framework.focus(); >; // remove selected option btnRemove.onclick = (e) => < e.preventDefault(); // save the selected options let selected = []; for (let i = 0; i < listbox.options.length; i++) < selected[i] = listbox.options[i].selected; >// remove all selected option let index = listbox.options.length; while (index--) < if (selected[index]) < listbox.remove(index); >> >;
Code language: JavaScript (javascript)
First, use the querySelector() method to select elements including the input text, button, and selection box:
const btnAdd = document.querySelector('#btnAdd'); const btnRemove = document.querySelector('#btnRemove'); const listbox = document.querySelector('#list'); const framework = document.querySelector('#framework');
Code language: JavaScript (javascript)
Second, attach the click event listener to the btnAdd button.
If the value of the input text is blank, we show an alert to inform the users that the name is required. Otherwise, we create a new option and add it to the selection box. After adding the option, we reset the entered text of the input text and set the focus to it.
btnAdd.addEventListener('click', (e) => < e.preventDefault(); // validate the option if (framework.value.trim() === '') < alert('Please enter the name.'); return; > // create a new option const option = new Option(framework.value, framework.value); // add it to the list listbox.add(option, undefined); // reset the value of the input framework.value = ''; framework.focus(); >);
Code language: JavaScript (javascript)
Third, register a click event listener to the btnRemove button. In the event listener, we save the selected options in an array and remove each of them.
btnRemove.addEventListener('click', (e) => < e.preventDefault(); // save the selected options let selected = []; for (let i = 0; i < listbox.options.length; i++) < selected[i] = listbox.options[i].selected; >// remove all selected option let index = listbox.options.length; while (index--) < if (selected[index]) < listbox.remove(index); >> >);
Code language: JavaScript (javascript)
Summary
- JavaScript uses the HTMLSelectElement type to represent the element.
- Use the add() method of the HTMLSelectElement to add an option to the element.
- Use the remove() method of the HTMLSelectElement to remove an option from the element.
Select options Collection
Find out how many options there are in a specific drop-down list:
More «Try it Yourself» examples below.
Description
The options collection returns a collection of all elements in a drop-down list.
Note: The elements in the collection are sorted as they appear in the source code.
Browser Support
Syntax
Properties
Property | Description |
---|---|
length | Returns the number of elements in the collection. |
Methods
Method | Description |
---|---|
[index] | Returns the element from the collection with the specified index (starts at 0). |
Technical Details
DOM Version: | Core Level 2 Document Object |
---|---|
Return Value: | An HTMLOptionsCollection Object, representing all elements in the element. The elements in the collection are sorted as they appear in the source code |
More Examples
Example
Get the text of the first option (index 0) in a drop-down list:
Example
Get the text of the first option (index 0) in a drop-down list:
Example
Get the text of the option with in a drop-down list:
Example
Add a «Kiwi» option at index position «1» in a drop-down list:
var x = document.getElementById(«mySelect»);
var c = document.createElement(«option»);
c.text = «Kiwi»;
x.options.add(c, 1);
Example
Remove the option with index «1» from a drop-down list:
Example
Loop through all options in a drop-down list, and output the text of each option:
var x = document.getElementById(«mySelect»);
var txt = «»;
var i;
for (i = 0; i < x.length; i++) txt = txt + x.options[i].text + "
«;
>
The result of txt will be:
Example
Choose an option in the drop-down list and output the text of the selected option in an element with >
var x = document.getElementById(«mySelect»);
var i = x.selectedIndex;
document.getElementById(«demo»).innerHTML = x.options[i].text;
Example
Change the options in a drop-down list depending on the selected option in another drop-down list:
var carsAndModels = <>;
carsAndModels[‘VO’] = [‘V70’, ‘XC60’, ‘XC90’];
carsAndModels[‘VW’] = [‘Golf’, ‘Polo’, ‘Scirocco’, ‘Touareg’];
carsAndModels[‘BMW’] = [‘M6’, ‘X5’, ‘Z3’];
function ChangeCarList() var carList = document.getElementById(«car»);
var modelList = document.getElementById(«carmodel»);
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) modelList.remove(0);
>
var cars = carsAndModels[selCar];
if (cars) var i;
for (i = 0; i < cars.length; i++) var car = new Option(cars[i], i);
modelList.options.add(car);
>
>
>