Skip to content

Instantly share code, notes, and snippets.

@brianpeiris
Created November 1, 2009 09:57
Show Gist options
  • Save brianpeiris/223444 to your computer and use it in GitHub Desktop.
Save brianpeiris/223444 to your computer and use it in GitHub Desktop.
Prototype dynamic multi-select
<!doctype html>
<html lang="en">
<head>
<title>dynamicMultiSelect</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
<style>
button {
display: block;
margin-top: 1em;
}
</style>
</head>
<body>
<p>
This prototype code uses jQuery to enhance the behaviour of a <code>&lt;select/&gt;</code> element.
The <code>&lt;option/&gt;</code> elements are rearranged so that selected elements are moved to the top of the list when the <code>&lt;select/&gt;</code> element loses focus. Unselected <code>&lt;option/&gt;</code> elements are arranged according to the original order.
</p>
<select multiple="multiple" size="4" name="testSelect">
<option>foo0</option>
<option>foo1</option>
<option>foo2</option>
<option>foo3</option>
<option>foo4</option>
<option>foo5</option>
<option>foo6</option>
<option>foo7</option>
<option>foo8</option>
<option>foo9</option>
</select>
<button>serialize</button>
<script type="text/javascript">var originalOrder;
$('select').blur(function () {
var $this = $(this);
if (!originalOrder) {
originalOrder = $this.find('option');
}
var selected = $this.find(':selected');
originalOrder.remove().prependTo(this);
selected.remove().prependTo(this);
});
$('button').click(function () {
console.dir($('select').serializeArray());
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment