Search Qodo.co.uk

Javascript: Swapping select box options

Javascript: Here’s a JavaScript function that let’s you swap options from one select box to another to allow users to choose the options they want. Be careful when using this type of functionalist as it could be inaccessible to some users and can cause problems when submitting your forms.

The important thing to remember about using this type of function is that you have to select all of the options in the select box before submitting for them to be sent to your server-side page. This type of script can pose accessibility problems as the normal behaviour of a select box is changed.

function swapSelectOptions(selectFrom,selectTo,swapAll) {
	if (typeof(selectFrom) == "string") {
		availableitems = document.getElementById(selectFrom);
	}
	if (typeof(selectTo) == "string") {
		selecteditems= document.getElementById(selectTo);
	}
	for (var i = 0; i < availableitems.length; i++) {
		if (availableitems.options[i].selected || swapAll) {
			selecteditems.options[selecteditems.options.length] = new Option(availableitems.options[i].text);
			selecteditems.options[selecteditems.options.length-1].value = availableitems.options[i].value;
			availableitems.options[i].selected = false;
		  	availableitems.options[i] = null;
			i--;
		}
	}
}

Download the example Javascript: Swapping select box options now!

Post Details

Blog Archives

Blog Categories

Comments

There are currently no comments on this post.

Leave Feedback

Your comments