HackerKarma HackerKarma - 1 month ago 5
HTML Question

HTML table rows custom sort using jQuery

I am sorting my table rows on a

Code/SKU
column.
Code/SKU
column may or may not contain the
-
(dash) which is my delimiter. The 3 digit code after
-
is my product rack number with a prefix between A-Z. I am trying to sort the products in an ascending order based on the rack number
irrespective of the prefix
. In case if the rack number is missing those products should be listed on the top.

For example, if the input
Code/SKU
column contains:

RIN65631-A24
PNT64705
CPC31378-D06


Then the output
Code/SKU column
should be sorted as:

PNT64705
CPC31378-D06
RIN65631-A24


Here is my JSFiddle

I am getting the desired output as stated above but if you look at my JSFiddle you will see that I am using multiple calls
$(this).find()
function to retrieve a particular element from the DOM which IMO is not necessary. There may be a better way to avoid the redundant find() calls and achieve the same output. Can someone help me in this regard?

EDIT:

Note: Sorting should be performed on the DOM ready event.

Answer

Use sortContent jquery PLugin :

 $('td.sku').sortContent({asc:true,
                         target:function(e){
                           return $(e).parent();
                         },helper:function(e){
                            var html=$(e).html().split('-'); 
                            if(html.length===2){return html[1]}
                             else {return ''}    
                          }
 });

See Demo

Explanation

  • target callbak : You sort according td element , However, tr should be sorted . So the target is tr which is the parent of td element.

  • helper : to identify the content to sort

UPDATE :

to sort just numeric characters, Helper callback should be as following :

var myhelper=function(e){
   var html=$(e).html().split('-'); 
    if(html.length===2){return 'b'+html[1].numeric()}
    else {return 'a'+html[0].numeric()}

};

See Demo v2

Comments