Javascript Form Select Change Options Tutorial Dynamic List Elements Html5
Summary: in this tutorial, you will learn how to dynamically add options to and remove options from a select box in JavaScript.
The HTMLSelectElement
type represents the <select>
element. It has the add()
method that dynamically adds an option to the <select>
element and the remove()
method that removes an option from the <select>
element:
-
add(option,existingOption)
– adds a new<option>
element to the<select>
before an existing option. -
remove(index)
– removes an option specified by the index from a<select>
.
Adding options
To add an option dynamically to a select box, you use these steps:
- First, create a new option.
- Second, add the option to the select box.
There are multiple ways to create an option dynamically and add it to a select box 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:
Code language: JavaScript ( javascript )
let newOption = new Option('Option Text','Option Value');
Then, call the add()
method of the select box object:
Code language: JavaScript ( javascript )
selectBox.add(newOption,undefined);
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
as the second argument, the method adds the new option to the end of the options list.
2) Using the DOM methods
First, construct a new option using DOM methods:
Code language: JavaScript ( javascript )
// 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');
Second, add the new option to the select box using the appendChild()
method:
Code language: JavaScript ( javascript )
// add the option to the select box selectBox.appendChild(newOption);
Removing Options
There are also multiple ways to dynamically remove options from a select box.
The first way is to use the remove()
method of the HTMLSelectElement
type. The following illustrates how to remove the first option:
Code language: CSS ( css )
selectBox .remove(0);
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
:
Code language: JavaScript ( javascript )
selectBox.options[0] = null;
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
:
Code language: JavaScript ( javascript )
// remove the first element: selectBox.removeChild(selectBox.options[0]);
To remove all options of a select box, you use the following code:
Code language: JavaScript ( javascript )
function removeAll(selectBox) { while (selectBox.options.length > 0) { selectBox.remove(0); } }
When you remove the first option, the select box moves another option as the first option. The removeAll()
function repeatedly removes the first option in the select box, therefore, it removes all the options.
Put it all together
We'll build a small application that allows users to add a new option from the value of an input text and to remove one or more selected options:
Code language: HTML, XML ( xml )
<!DOCTYPE html> <html> <head> <title>JavaScript Selected Value</title> <link href="css/selectbox.css" rel="stylesheet"> </head> <body> <div id="container"> <form> <label for="name">Framework:</label> <input type="text" id="name" 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> const btnAdd = document.querySelector('#btnAdd'); const btnRemove = document.querySelector('#btnRemove'); const sb = document.querySelector('#list'); const name = document.querySelector('#name'); btnAdd.onclick = (e) => { e.preventDefault(); // validate the option if (name.value == '') { alert('Please enter the name.'); return; } // create a new option const option = new Option(name.value, name.value); // add it to the list sb.add(option, undefined); // reset the value of the input name.value = ''; name.focus(); }; // remove selected option btnRemove.onclick = (e) => { e.preventDefault(); // save the selected option let selected = []; for (let i = 0; i < sb.options.length; i++) { selected[i] = sb.options[i].selected; } // remove all selected option let index = sb.options.length; while (index--) { if (selected[index]) { sb.remove(index); } } }; </script> </body> </html>
How it works:
First, use the querySelector()
method to select elements including the input text, button, and selection box:
Code language: JavaScript ( javascript )
const name = document.querySelector('#name'); const btnAdd = document.querySelector('#btnAdd'); const btnRemove = document.querySelector('#btnRemove'); const sb = document.querySelector('#list');
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.
Code language: JavaScript ( javascript )
btnAdd.onclick = (e) => { e.preventDefault(); // validate the option if (name.value == '') { alert('Please enter the name.'); return; } // create a new option const option = new Option(name.value, name.value); // add it to the list sb.add(option, undefined); // reset the value of the input name.value = ''; name.focus(); };
Third, register a click event listener to the btnRemove
button. In the event listener, we save the selected options in an array first and remove each of them then.
Code language: JavaScript ( javascript )
// remove selected option btnRemove.onclick = (e) => { e.preventDefault(); // save the selected option let selected = []; for (let i = 0; i < sb.options.length; i++) { selected[i] = sb.options[i].selected; } // remove all selected option let index = sb.options.length; while (index--) { if (selected[index]) { sb.remove(index); } } };
In this tutorial, you have learned how to add options to and remove options from a select box using JavaScript.
Was this tutorial helpful ?
Javascript Form Select Change Options Tutorial Dynamic List Elements Html5
Source: https://www.javascripttutorial.net/javascript-dom/javascript-add-remove-options/
0 Response to "Javascript Form Select Change Options Tutorial Dynamic List Elements Html5"
Post a Comment