In this article I will explain with an example, how to move selected Items to Top of ListBox using jQuery.
When an Item (Option) is selected in the ListBox, it will be removed from the List and again added to the ListBox at 0th Index (First Position) using jQuery.
Moving Selected Items to Top of ListBox using jQuery
The ListBox has been assigned a jQuery OnClick event handler.
Inside the OnClick event handler, a loop is executed over the Items (Options) of the ListBox and the selected Items (Options) are removed from ListBox and added into a JavaScript Array.
Finally, a loop is executed over the JavaScript Array and the selected Items (Options) are added to the ListBox at 0th Index (First Position) using jQuery.
<select id="lstFruits" multiple="multiple" style="height: 95px">
<option value="1">Mango</option>
<option value="2">Apple</option>
<option value="3">Banana</option>
<option value="4">Pineapple</option>
<option value="5">Orange</option>
<option value="6">Lemon</option>
<option value="7">Guava</option>
</select>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#lstFruits", function () {
var lst = $(this);
var selected = new Array();
lst.find("OPTION").each(function () {
if ($(this).is(":selected")) {
selected.push($(this));
$(this).remove();
}
$(selected).each(function () {
lst.prepend($(this));
});
});
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads