Javascript options new option

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.

Читайте также:  Using if in java script

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.

Источник

HTMLOptionElement: Option() constructor

The Option() constructor creates a new HTMLOptionElement .

Syntax

new Option() new Option(text) new Option(text, value) new Option(text, value, defaultSelected) new Option(text, value, defaultSelected, selected) 

Parameters

A string representing the content of the element, i.e. the displayed text. If this is not specified, a default value of «» (empty string) is used.

A value of either true or false that sets the option’s selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected.

Examples

Just add new options

/* assuming we have the following HTML */ const s = document.getElementById("s"); const options = [Four, Five, Six]; options.forEach((element, key) =>  s[key] = new Option(element, key); >); 

Append options with different parameters

/* assuming we have the following HTML  */ const s = document.getElementById("s"); const options = ["zero", "one", "two"]; options.forEach((element, key) =>  if (element === "zero")  s[key] = new Option(element, s.options.length, false, false); > if (element === "one")  s[key] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute > if (element === "two")  s[key] = new Option(element, s.options.length, false, true); // Just will be selected in "view" > >); /* Result  */ 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

HTMLSelectElement: add() method

The HTMLSelectElement.add() method adds an element to the collection of option elements for this select element.

Syntax

Parameters

An element of the collection, or an index of type long, representing the item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection.

Return value

Exceptions

Thrown if the item passed to the method is an ancestor of the HTMLSelectElement .

Examples

Creating Elements from Scratch

const sel = document.createElement("select"); const opt1 = document.createElement("option"); const opt2 = document.createElement("option"); opt1.value = "1"; opt1.text = "Option: Value 1"; opt2.value = "2"; opt2.text = "Option: Value 2"; sel.add(opt1, null); sel.add(opt2, null); /* Produces the following, conceptually:  */ 

The before parameter is optional. So the following is accepted.

Append to an Existing Collection

const sel = document.getElementById("existingList"); const opt = document.createElement("option"); opt.value = "3"; opt.text = "Option: Value 3"; sel.add(opt, null); /* Takes the existing following select object:  And changes it to:  */ 

The before parameter is optional. So the following is accepted.

Inserting to an Existing Collection

const sel = document.getElementById("existingList"); const opt = document.createElement("option"); opt.value = "3"; opt.text = "Option: Value 3"; sel.add(opt, sel.options[1]); /* Takes the existing following select object:  And changes it to:  */ 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью