Html select js add 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.

Читайте также:  How to include HTML page with jQuery

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.

Источник

Manipulation of HTML Select Element with Javascript

Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.

Important Properties and Methods of Select Element

  • value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
  • options : It gives the list of all option elements in the select
  • selectedOptions : It gives the list of option elements that are currently selected
  • selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
  • add() : This method adds a new option to the list of options
  • remove() : This method removes an option from the select element

Important Properties of Option Element

  • value : It gives the value of the option
  • text : It gives the text inside the option
  • selected : It tells whether the option is selected or not

Setting Value of Select Element

For a single valued select, setting its value can be done with the value or the selectedIndex property.

// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2; 

For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.

  
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true; 

This will obviously work for single valued select also, but using the value property is much direct for them.

Getting the Value and Text/Label of the Selected Options

The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.

// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value; 

For a multiple select element, you can loop over the list to get all selected options.

  
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5 

Adding an Option

The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.

var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2); 

Deleting an Option

The remove method can be used to delete an option at a specified index.

// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1); 

Источник

Select add() Method

The add() method is used to add an option to a drop-down list.

Tip: To remove an option from a drop-down list, use the remove() method.

Browser Support

Syntax

Parameter Values

Parameter Description
option Required. Specifies the option to add. Must be an option or optgroup element
index Optional. An integer that specifies the index position for where the new option element should be inserted. Index starts at 0. If no index is specified, the new option will be inserted at the end of the list

Technical Details

More Examples

Example

Add a «Kiwi» option at the beginning of a drop-down list:

var x = document.getElementById(«mySelect»);
var option = document.createElement(«option»);
option.text = «Kiwi»;
x.add(option, x[0]);

Example

Add a «Kiwi» option at index position «2» of a drop-down list:

var x = document.getElementById(«mySelect»);
var option = document.createElement(«option»);
option.text = «Kiwi»;
x.add(option, x[2]);

Example

Add an option before a selected option in a drop-down list:

var x = document.getElementById(«mySelect»);
if (x.selectedIndex >= 0) var option = document.createElement(«option»);
option.text = «Kiwi»;
var sel = x.options[x.selectedIndex];
x.add(option, sel);
>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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