Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a select box

form elements

Sorting a select box

by  BillyRayPreachersSon  Posted    (Edited  )
This code should give you an idea of how to sort a select box. The code has been tested in IE6, but should work in most modern DOM-compliant browsers.

Update May 2006: Also tested working fine in Firefox/Win 1.5.0.2.

Code:
<html>
<head>
	<script type="text/javascript">
	<!--

		// sort function - ascending (case-insensitive)
		function sortFuncAsc(record1, record2) {
			var value1 = record1.optText.toLowerCase();
			var value2 = record2.optText.toLowerCase();
			if (value1 > value2) return(1);
			if (value1 < value2) return(-1);
			return(0);
		}

		// sort function - descending (case-insensitive)
		function sortFuncDesc(record1, record2) {
			var value1 = record1.optText.toLowerCase();
			var value2 = record2.optText.toLowerCase();
			if (value1 > value2) return(-1);
			if (value1 < value2) return(1);
			return(0);
		}

		function sortSelect(selectToSort, ascendingOrder) {
			if (arguments.length == 1) ascendingOrder = true;	// default to ascending sort

			// copy options into an array
			var myOptions = [];
			for (var loop=0; loop<selectToSort.options.length; loop++) {
				myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
			}

			// sort array
			if (ascendingOrder) {
				myOptions.sort(sortFuncAsc);
			} else {
				myOptions.sort(sortFuncDesc);
			}

			// copy sorted options from array back to select box
			selectToSort.options.length = 0;
			for (var loop=0; loop<myOptions.length; loop++) {
				var optObj = document.createElement('option');
				optObj.text = myOptions[loop].optText;
				optObj.value = myOptions[loop].optValue;
				selectToSort.options.add(optObj);
			}
		}
	//-->
	</script>
</head>

<body>
	<form>
		<select name="mySelect">
			<option value="3">Cat</option>
			<option value="4">Dog</option>
			<option value="2">Fish</option>
			<option value="1">Bird</option>
		</select>
		<br />
		<input type="button" onclick="sortSelect(this.form['mySelect'], true);" value="Sort (Asc)">
		<input type="button" onclick="sortSelect(this.form['mySelect'], false);" value="Sort (Desc)">
	</form>
</body>
</html>

Enjoy!

Dan


[link http://www.coedit.co.uk/][color #00486F]Coedit Limited[/color][/link][color #000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
http://www.codecouch.com/dan/[/tt]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top