Sorting Of <li> Elements Using jQuery sort() Method Not Working (Refresh Page Only) In ASP.NET
Given the simple sorting code below which changes the order of <li> elements to ascending order and assuming that the text content of each li elements are numbers.
The code should work only to find out that the page will only refresh after the button click. And then the re-arranging of the elements are discarded. The simple fix to this issue is to add the preventDefault() to prevent the button's default behavior that is to post back.
Fiddle: Sort Unordered List Items
$(function () { $('#sortList').click(function (e) { // Select all the li items var numbersList = $('#numbersList li'); numbersList.sort(function (a, b) { return parseInt($(a).text(), 10) > parseInt($(a).text(), 10); }).appendTo(numbersList.parent()); }); });
$(function () { $('#sortList').click(function (e) { e.preventDefault(); var numbersList = $('#numbersList li'); numbersList.sort(function (a, b) { var temp1 = parseInt($(a).text(), 10); var temp2 = parseInt($(b).text(), 10); return (temp1 < temp2) ? -1 : (temp1 > temp2) ? 1: 0; }).appendTo(numbersList.parent()); }); });
Comments
Post a Comment