Javascript remove items from select list

Javascript remove items from select list

Posted: nerevarthelord Date: 21.07.2017

The following Javascript functions are hereby granted to the public domain.

javascript remove items from select list

Read below for how to implement these functions. The standard way to clear all the options is to simply set the options.

That function is listed below, and is fast enough when there are not that many options in the drop-down list a. This method is also the most browser-compatible. There are many sample codes on the Internet that loop through all the options in a for loop. Each option is removed one at a time with a call to remove or by setting them to null.

Javascript Clear Select Options Fast

This is unnecessary at best, and slow and inefficient at best. The simple method requires fewer lines of code and runs faster. The problem comes when you have s of options in the drop-down list.

This is most likely not due to the Javascript speed, but an operating system limitation. Finally, I came up the idea of removing javascript remove items from select list drop-down list completely, and adding back an empty copy of the original one.

javascript remove items from select list

This is possible with calls to cloneNode and replaceChild on the document object. A new one is shallow cloned from the old one, and inserted back into the page. This is a O 1 or constant time operation.

The function is suitable for very large select boxes. You can test this in your browser by adding or more automatic day trading robot above, and then clicking one of the remove buttons. Note, if you add too many options, your browser may hang for awhile.

JavaScript to Add and Remove Options in a Select Box

In IE 6, the standard method has the annoying effect of scrolling through the options while they are being erased. The fast method avoids this. The alternate fast method was provided by Victor T.

References to the original SELECT object will become invalidated! If you had created references to the select object in your code, make sure to re-initialize those references again after calling the function.

Javascript: Remove / Delete a Select Option from List

This is because the function will destroy the original SELECT object. The function returns a reference to the new SELECT object. You should set a fixed width, so that the list does not annoyingly change size as options are added and removed. An example is below. Unfortunately, IE 6 and 7 will not allow you to do that, so you will have to stick with the above stand-alone functions for now.

javascript remove items from select list

The above code was tested in IE6, FireFox 3, and Opera 9. This content is provided as-is. The information may be incorrect.

Rating 4,5 stars - 933 reviews
inserted by FC2 system