Javascript Reference: Dropdown - Move item up/down a dropdown



The following snippet will shift a selected option up/down a defined dropdown/listbox using javascript.

Usage:
 
<input type="button" onclick="shift('items', 'up')" value="Up" />
<input type="button" onclick="shift('items', 'down')" value="Down"/>
 

 
function shift(id, direction)
{
	var items = document.getElementById(id);
	var oldIndex = items.selectedIndex;
 
	if (oldIndex != -1)
	{	
		with (items)
		{
			if (direction == 'up')
				var newIndex = (oldIndex == 0) ? options.length - 1 : oldIndex - 1;
			else if (direction == 'down')
				var newIndex = (oldIndex == options.length - 1) ? 0 : oldIndex + 1;
			else
				return false;
 
			var a = new Option(options[oldIndex].text, options[oldIndex].value);
			var b = new Option(options[newIndex].text, options[newIndex].value);
			options[oldIndex] = b;
			options[newIndex] = a;					
			selectedIndex = newIndex;
		}
	}
}
 





No Entries Found

Post comment

Name *
Email
Title
Body *
Security code
*
* Required fields

Latest Articles

C# : Snippets


Collection of C# snippets
2010-05-22 01:06:19

MS SQL : Snippets


Collection of MS SQL snippets
2010-05-22 00:55:15

JavaScript : Snippets


Collection of JavaScript snippets
2010-05-22 00:37:57

ASP.net: Snippets


Collection of ASP.net snippets
2010-05-22 00:29:56

PHP: Snippets


Collection of PHP snippets
2010-05-22 00:06:45

Parallel Language Reference : Strings


a Parallel reference of programming languages
2009-09-10 12:48:23

PHP Tutorial: Developing a Login – Part 1


a tutorial explaining how to develop a simple login using PHP and MySQL
2009-09-05 18:26:47

Event driven programming in PHP


An article looking at adding some kind of event driven model to PHP 5
2008-07-28 12:48:09

How to create your own RSS Reader


It is very simple creating your own rss reader, the following article looks at a few methods of doing this.
2008-06-23 13:18:25

Javascript Reference: Dropdown


A quick reference about working with dropdown boxes (select element) in javascript.
2007-02-17 16:36:41

Top 5 Articles

Programming humor


Collection of funny programming articles
2006-10-08 14:23:43

How to create your own RSS Reader


It is very simple creating your own rss reader, the following article looks at a few methods of doing this.
2008-06-23 13:18:25

Javascript Reference: Dropdown


A quick reference about working with dropdown boxes (select element) in javascript.
2007-02-17 16:36:41

PHP: Snippets


Collection of PHP snippets
2010-05-22 00:06:45

Event driven programming in PHP


An article looking at adding some kind of event driven model to PHP 5
2008-07-28 12:48:09