jQuery : Sort Dropdown list items using jQuery
Javascript
<script type='text/javascript'>
$(document).ready(function() {
$('#btnSort').click(function(e) {
$("#ddlList").html($('#ddlList option').sort(function(x, y) {
return $(x).text() < $(y).text() ? -1 : 1;
}))
$("#ddlList").get(0).selectedIndex = 0;
e.preventDefault();
});
$('#btnSortVal').click(function(e) {
$("#ddlList").html($('#ddlList option').sort(function(x, y) {
return $(x).val() < $(y).val() ? -1 : 1;
}))
$("#ddlList").get(0).selectedIndex = 0;
e.preventDefault();
});
});
</script>
HTML
<select id="ddlList">
<option value="3">Three</option>
<option value="1">One</option>
<option value="0">Zero</option>
<option value="2">Two</option>
<option value="8">Eight</option>
</select>
<br/><br/>
<input type="button" id="btnSort" Value=" Sort Dropdown By Text " />
<input type="button" id="btnSortVal" Value=" Sort Dropdown By Value " />
No comments:
Post a Comment