TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript JavaScript Moving option elements between HTML select lists

JavaScript Moving option elements between HTML select lists

User Rating: / 0
PoorBest 

Moving option elements between HTML select lists when used with Reorder option elements of an HTML select has been the one of the most useful JavaScript function sets I have created. I have reused this again and again. You have two select lists the first holds all the possible values and the second will hold the users choice.

This script contains one method called swapElement(from,to) which takes two arguements from and to. From and to contain the Id of the selects which the element is coming from and going to. There is nothing more to the script than that.

function swapElement(fromList,toList){
	var selectOptions = document.getElementById(fromList);
	for (var i = 0; i < selectOptions.length; i++) {
		var opt = selectOptions[i];
		if (opt.selected) {
			document.getElementById(fromList).removeChild(opt);
			document.getElementById(toList).appendChild(opt);
			i--;
		}
	}
}

Explanation

This is best called from buttons with onclick usually named something imaginative like '<' & '>'. In the example when you select an option in Select 1. and select > you call swapElement('select1','select2') which takes all the elements of Select 1. and loops over them in the for loop to identify the selected options. When a selected option is identified it is removed from Select 1. and moved to Select 2.