Donate

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.
$(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());
 });
});
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.
$(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());
	});
});
Fiddle: Sort Unordered List Items

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.