Tuesday, July 21, 2009

jQuery: Few tips when you work with Tablesorter plugin

I like Tablesorter plugin. It is very useful. It can save you a lot of time by sorting items on client side instead of any(partial or full) postback to the server. What I discovered is that sometimes it takes time before it starts to work for you. So, here are few tips for you:

* use $.tablesorter.addParser whenever you can. It is useful cause in examples you can find on Tablesorter documentation all examples handle with plain text in cells. In my case I had few spans, images and so on as a content of span.

*In format property of addParser you define what should be done when content of cell is available. Since I like to use jQuery I realize that jQuery is not appliable to content I get. So weird and so strange. After sometime I got it! jQuery requests root html element and content you get from parameter in format function doesn't have root element. So, in order to get content workable with jQuery create something like this
var innerContent = $("<root>" + s + "</root>"). After that you can apply jQuery. As example I provide code snippet:

$.tablesorter.addParser({
id: 'currencySwiss',
is: function(s) {
return false;
},
format: function(s) {
var innerContent = $("<root>" + s + "</root>");
if (isElectronicProduct === 'False') {
if ($("span[id$='ctlNetPriceMediaLabel']", innerContent)[0].innerHTML === "") {
return 10000000;
} else {
return $("span[id$='ctlNetPriceMediaLabel']", innerContent)[0].innerHTML;
}
} else {//electronic product
if ($("span[id$='ctlNetPriceLabel']", innerContent)[0].innerHTML === "") {
return 10000000;
} else {
return $("span[id$='ctlNetPriceLabel']", innerContent)[0].innerHTML;
}
}
},

type: 'numeric'
});

Cheers,