Adding new items to list fields

Jake Howlett, 13 November 2000

Category: Forms; Keywords: List select drop down

As an example, this is not particularly useful if you are looking for something that is "Plug & Play". However there are times when the methods that are demonstrated may be applicable. Stick with me on this one.

Look at the list of colours in the box below. Click on one of them and it will magically be swapped over in to the "empty" list.



The code required to do this is:

function addNewOption( lst, fld, sel, rmv ){
var txt = lst.options[lst.selectedIndex].text;
var val = lst.options[lst.selectedIndex].value;
var newElem = document.createElement("OPTION");
newElem.text = txt;
newElem.value = (val == '') ? txt : val;
fld.add(newElem);
if (sel) fld.selectedIndex = fld.options.length-1;
if (rmv) lst.options.remove(lst.selectedIndex);
}


You can place calls to this function anywhere you like, such as the onChange, onClick, onLoad events or behind a button. In the above example it is in the "onClick" event of the source list:

<select name="source" size="8" onClick="if (this.selectedIndex > 0) addNewOption( this, this.form.dynamic, false, true );">
*

*This call first checks that the user did not click on the first option which is only there as a hint. If you do not use this option then simply remove the "if" statement.

The three arguments passed in to the function allow it to be fairly generic in the way it gets used:

The source and destination fields do not have to be multi-line select elements. You can use the above function with any of the <select> element types e.g. drop-down lists.



Note: The above function is Internet Explorer friendly only. This is due mainly to the fact that its DOM (Document Object Model) supports the add() and remove() methods of the select element's option collection. You can do the above in Netscape using the following functions:

function addNewOption(lst, fld, sel, rmv) {
for(var i=0; i < lst.options.length; i++) {
if(lst.options[i].selected && lst.options[i].value != "") {
var no = new Option();
no.value = lst.options[i].value;
no.text = lst.options[i].text;
fld.options[fld.options.length] = no;
if (sel) fld.selectedIndex = fld.options.length-1;
if (rmv) {
lst.options[i].value = "";
lst.options[i].text = "";
BumpUp(lst);
}
}
}
}

function BumpUp(box) {
for(var i=0; i<box.options.length; i++) {
if(box.options[i].value == "") {
for(var j=i; j<box.options.length-1; j++) {
box.options[j].value = box.options[j+1].value;
box.options[j].text = box.options[j+1].text;
}
var ln = i;
break;
}
}
if( ln < box.options.length) {
box.options.length -= 1;
BumpUp(box);
}
}
GOOD LUCK !