Tuesday 11 August 2015

How to sort a list items alphabetically using JavaScript

Hello All,
Working with HTML and JavaScript, many time we render html in our page with the help of JavaScript, like adding a list that has many list items.
To show that list in a alphabetical order (ascending or descending order) in our HTML page using JavaScript we can use following block of code:
function SortList(elementId) {    var mylist = $("#" + elementId);    $(mylist).children("li").sort(function (item1, item2) {        var compFirst = $(item1).text().toUpperCase();        var compSecond = $(item2).text().toUpperCase();        if (!((compFirst != "") || (compSecond == "DEFAULT"))) {            return (compFirst < compSecond) ? -1 : (compFirst > compSecond) ? 1 : 0;

To view full blog about How to sort a list items alphabetically using JavaScript visit FindNerd.
You can also ask questions of javascript at our Javascript Developer Forum Section.

No comments:

Post a Comment