Forked from anonymous/Sort-Dropdown-list-alphabetically-jquery.markdown
Last active
August 29, 2015 14:14
-
-
Save ChunAllen/59302c93a79e27d22393 to your computer and use it in GitHub Desktop.
Sorting values asc and desc on multiple dropdowns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<select class="ddlList"> | |
<option value="3">Three</option> | |
<option value="1">One</option> | |
<option value="1">one</option> | |
<option value="1">a</option> | |
<option value="1">b</option> | |
<option value="1">A</option> | |
<option value="1">B</option> | |
<option value="0">Zero</option> | |
<option value="2">Two</option> | |
<option value="8">Eight</option> | |
</select> | |
<select class="ddlList"> | |
<option value="3">Three</option> | |
<option value="1">One</option> | |
<option value="1">one</option> | |
<option value="1">a</option> | |
<option value="1">b</option> | |
<option value="1">A</option> | |
<option value="1">B</option> | |
<option value="0">Zero</option> | |
<option value="2">Two</option> | |
<option value="8">Eight</option> | |
</select> | |
<input type="button" id="btnSort" Value=" Sort Dropdown By Text " /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//, attr, order | |
var sortSelect = function (select, attr, order) { | |
if(attr === 'text'){ | |
if(order === 'asc'){ | |
$(select).html($(select).children('option').sort(function (x, y) { | |
return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1; | |
})); | |
$(select).get(0).selectedIndex = 0; | |
e.preventDefault(); | |
}// end asc | |
if(order === 'desc'){ | |
$(select).html($(select).children('option').sort(function (y, x) { | |
return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1; | |
})); | |
$(select).get(0).selectedIndex = 0; | |
e.preventDefault(); | |
}// end desc | |
} | |
}; | |
//, attr, order | |
$(document).ready(function () { | |
$('#btnSort').click(function (e) { | |
$(".ddlList").each(function(){ | |
sortSelect($(this), 'text', 'asc'); | |
}) | |
}); // event listener click | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment