Tuesday, April 30, 2013

Sort Items in Dropdown List Using Jquery






HTML:

<form id="form1" runat="server">
<div class="smallDiv">
<h2>Click on the Sort Button to Sort the DropDownList </h2>
<asp:DropDownList ID="DDL" runat="server" >
<asp:ListItem Text="Item3" Value="3"></asp:ListItem>
<asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item4" Value="4"></asp:ListItem>
<asp:ListItem Text="Item5" Value="5"></asp:ListItem>
<asp:ListItem Text="Item2" Value="2"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Button ID="btnSort" runat="server" Text="Sort" />
<p id="para"></p>
<br /><br />
Tip: Items are sorted in an Ascending order
</div>
</form>


Jquery:
<script type="text/javascript">
$(function() {
$('input[id$=btnSort]').click(function(e) {
e.preventDefault();
var sortedDdl = $.makeArray($('select[id$=DDL] option'))
.sort(function(o, n) {
return $(o).text() < $(n).text() ? -1 : 1;
});
$("select[id$=DDL]").html(sortedDdl).val("1");
$("#para").html("Items were Sorted!");
$(this).attr("disabled", "disabled");
});
});
</script>

Explanation:

In the code shown above, when the user clicks on the Sort button, the <option> elements are converted to an array using $.makeArray().

$.makeArray($('select[id$=DDL] option'))

The JavaScript built-in sort() function is used on this array, which does an in-place sort of the array.

$.makeArray($('select[id$=DDL] option'))
.sort(function(o, n) {
return $(o).text() < $(n).text() ? -1 : 1;
});

The final step is to empty the contents of the DropDownList and then use the .html() to replace the existing <options> with the sorted <options>.

$("select[id$=DDL]").empty().html(sorted)

The val("1") sets the first option as selected, after the sorting has been done.

1 comment:
Write comments
Recommended Posts × +