swap multiple javascript

This little javascript function do a swap between the value and the text of a single or some multiple options.



Source (Downloaded and tested: sept-17-2005 01:31:00)

ACCORDING TO this Website http://docs.sun.com/source/816-6408-10/select.htm (Last Updated: 05/28/99 12:00:23)
For Select objects that can have multiple selections (that is, the SELECT tag has the MULTIPLE attribute), the selectedIndex property is not very useful. In this case, it returns the index of the first selection. To find all the selected options, you have to loop and test each option individually. For example, to print a list of all selected options in a selection list named mySelect, you could use code such as this:

  document.write("You've selected the following options:\n")
  for (var i = 0; i < mySelect.options.length; i++) {
 	if (mySelect.options[i].selected)
 		document.write(" mySelect.options[i].text\n")
 }


But they are wrong, it works with selectedIndex! See:

They say that you cannot use selectedIndex because it returns only the first selectedIndex in the list of selectedIndexes and if you set it to false (unselected), all the selected are set to false (unselected)! With a loop such a "for" loop, the Options are read one by one to know if there are selected to apply the function on them, waisting time! Using selectedIndex, perhaps the options are not read again one by one ? It seems to be faster with selectedIndex, but it needs a longer list to test that, and a watch!

Here are the two sources of the functions

// with a loop such "for": without selectedIndex!
function swapm() {
	if (document.forms.f.s.selectedIndex!=-1) {
		for (var i = 0; i < document.forms.f.s.length; i++) {
			if (document.forms.f.s.options[i].selected==true) {
				var val=document.forms.f.s.options[i].text;
				document.forms.f.s.options[i].text=document.forms.f.s.options[i].value;
				document.forms.f.s.options[i].value=val;				
				document.forms.f.s.options[i].selected=false;
			}
		}
	}

}

// with selectedIndex: IT WORKS WELL !!!
function swapn() {
	while (document.forms.f.s.selectedIndex>=0) {
		var val=document.forms.f.s.options[document.forms.f.s.selectedIndex].text;
		document.forms.f.s.options[document.forms.f.s.selectedIndex].text=document.forms.f.s.options[document.forms.f.s.selectedIndex].value;
		document.forms.f.s.options[document.forms.f.s.selectedIndex].value=val;
		document.forms.f.s.options[document.forms.f.s.selectedIndex].selected=false;
	}
}