Over a million developers have joined DZone.

HTML/JavaScript - Select List - Add/Remove Options (DOM)

·
from http://www.mredkj.com/tutorials/tutorial005.html


Overview

    * Insert Before Selected - A new option is created and added above the selected option (as determined by selectedIndex). If none are selected, then no option is added.
    * Remove Selected - Deletes the selected option (or options) from the list. If no options are selected, no options are deleted.
    * Append Last - No matter what is selected, a new option is added at the end.
    * Remove Last - No matter what is selected, the last option is deleted from the list.


Explanation

According to DOM Level 1, the following is the syntax for the add and remove methods in HTMLSelectElement:

void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

The add method takes two arguments: the element to add, and the element to insert before. The spec also says you can add to the end of the list by passing null as the second argument.

The remove method just takes a number: the index of the option to be removed. 


The JavaScript





The HTML

Insert Before Selected
Remove Selected

Append Last
Remove Last
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}