TableSorter : Filter digits with comma as decimal sign - tablesorter

With jQuery TableSorter, I can't filter a column correctly that contains European formatted digits (dot every 3 digit and comma as decimal sign). Anyway, sorting work like a charm.
See my problem here : http://jsfiddle.net/Ted22/9tBgZ/13/
I work with this piece of code :
jQuery.tablesorter.addParser({
id: "commaDigit",
is: function(s, table) {
var c = table.config;
return $.tablesorter.isDigit(s.replace(/[,.]/g, ""), c);
},
format: function(s) {
return $.tablesorter.formatFloat(s.replace(/[,.]/g, ""));
},
parsed: false,
type: "numeric"
});
Can you help me ?
Thanks in adavance !
Ted

Just set the usNumberFormat option to false (demo)

Related

custom sort order in tablesorter - jquery

I do use tablesorter (https://mottie.github.io/tablesorter/docs/index.html)
To sort my HTML tables.
I have one sorting I cannot find howtoo. ie.
(4)
(dns)
1
2
3
5
dns
is to be sorted as:
1
2
3
(4)
5
(dns)
dns
in short: the () are to be ignored and numeric sort, numeric first then alphabetical.
I have seen how to replace characters, (doesn't work as "empty" as some rank too)
The parsers I have seen thusfar require me to create per header and known value to be replaced.
ie:
$.tablesorter.addParser({
id: 'nummeriek',
is: function(s) {
return false;
},
format: function(s) {
// format your data for normalization
return s.toLowerCase().replace('dns',999).replace('(dns)',999).replace('(4)',4);
},
type: 'numeric'
});
$('.tablesorter').tablesorter({
headers: {
6: {
sorter:'nummeriek'
}
}
});
If I have to do this for every possible table content I end up creating hundreds of replace() statements. as I have scores from 1 to 100 Thus (1) to (100) is possible too...
There must be an easier way. Any help is much appreciated.
The default digit parser "assumes" that numbers wrapped in parentheses are negative; this is a common method of indicating a negative number in accounting (ref).
To get around this, you will need to slightly modify the parser (demo)
$(function() {
$.tablesorter.addParser({
id: 'nummeriek',
is: function(s) {
return false;
},
format: function(str) {
// format your data for normalization
var s = str.replace(/[()]/g, ""),
n = parseFloat(s);
return !isNaN(n) && isFinite(n) ? n : s;
},
type: 'numeric'
});
$('.tablesorter').tablesorter({
headers: {
0: {
sorter: 'nummeriek'
}
}
});
});
Note: this parser always returns a non-numeric string without parentheses, e.g. "(dns)" will become "dns". I kept it this way so the "(dns)" entries will sort as if they are "dns".

tablesorter to sort columns which has <br> within them

I have a table which has one of the column's as datetime: eg: 1/11/2011 12:34 PM
Unfortunately, the width of the column does not allow me to display datetime in full length in one line, hence I am displaying the contents in two lines, like
1/11/2011
12:34 PM
But tablesorter will not work if the column contents have a <br> in them. Any idea how I can achieve sorting via tablesorter for this issue? I am having tablesorter revision 2.0.5b. I cannot upgrade to newer version because it might break existing features of the rails app.
tablesorter is the jquery plugin
You'll probably need a custom parser to remove the carriage return; honestly, I don't think a <br> needs to be added if the text is allowed to wrap, and you set a width for that column.
Anyway, try this code (demo)
$(function () {
$.tablesorter.addParser({
// set a unique id
id: 'date',
is: function (s, table, cell) {
// return false so this parser is not auto detected
return false;
},
format: function (s, table, cell, cellIndex) {
// replace extra spacing/carriage returns
var str = s.replace(/\s+/g," "),
date = new Date( str );
return date instanceof Date && isFinite(date) ? date.getTime() : s;
},
// set type, either numeric or text
type: 'numeric'
});
$('table').tablesorter({
theme: 'blue',
headers: {
7: { sorter: 'date' }
}
});
});

Select2 searches inside the html of the formatted options

I am using the select2 widget, and I need to display the search results formatted as html.
So I am using it like this:
function formatMyItem(myItem) {
return defaultEscapeMarkup(myItem.someDescription) + " <strong>(" + myItem.someOtherValue + ")</strong>";
}
function defaultEscapeMarkup(markup) {
var replace_map = {
'\\': '\',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/'
};
return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
return replace_map[match];
});
}
var suggestionValues = [];
for (var i = 0; i < myData.length; i++) {
var myItem = myData[i];
suggestionValues.push({
id: myItem.someKey,
text: formatMyItem(myItem)
});
}
$mySelect.select2({
width: 'resolve',
multiple: true,
data: suggestionValues,
escapeMarkup: function(m) {
// Do not escape HTML in the select options text
return m;
}
});
But now when the user searches for something, that term is searched inside the HTML of the option.
For example, if the user searches for "strong" (assumming that some descriptions can contain the word "strong"), then select2 will suggest all the values (because all of them contain "strong").
Also, when the user searches for "<" (assuming that some descriptions contain mathematical symbols), then select2 will return all values (because all of them contain html tags), but will not highlight the actual "less than" symbol in the descriptions, because they have been actually converted to "& lt;".
How can I make select2 not search inside the html tags?
Ok, it seems the solution was actually quite simple :D
I added the following:
$mySelect.select2({
width: 'resolve',
multiple: true,
data: suggestionValues,
escapeMarkup: function(m) {
// Do not escape HTML in the select options text
return m;
},
matcher: function(term, text) {
// Search the term in the formatted text
return $("<div/>").html(text).text().toUpperCase().indexOf(term.toUpperCase())>=0;
}
});
So now when the user searches for "strong" they get only the relevant results.
But now there is another issue:
Now, if the user searches for "<", then select2 will highlight the "<" inside the strong tag.
It seems that I need to also "patch" somehow the search-results highlighter...
EDIT : Coming back to this, it seems that the solution for the highlighting is not so easy...
The default implementation in select2 is like this:
formatResult: function(result, container, query, escapeMarkup) {
var markup=[];
markMatch(result.text, query.term, markup, escapeMarkup);
return markup.join("");
},
.......
function markMatch(text, term, markup, escapeMarkup) {
var match=text.toUpperCase().indexOf(term.toUpperCase()),
tl=term.length;
if (match<0) {
markup.push(escapeMarkup(text));
return;
}
markup.push(escapeMarkup(text.substring(0, match)));
markup.push("<span class='select2-match'>");
markup.push(escapeMarkup(text.substring(match, match + tl)));
markup.push("</span>");
markup.push(escapeMarkup(text.substring(match + tl, text.length)));
}
Somehow I need to replace these two functions, but I cannot find an easy solution for mapping from the range of characters in the formatted HTML (the search-term to highlight) back to the source html (so that I can add the < span class='select2-match' > ) ...
If any of you has better solutions, please feel free to share them...

Putting commas in amount field in Razor syntax

I am developing a MVC app. I have some amount fields. by default it showing numbers without comma separation. for e.g. if I have amount 500000000 then I want to display it like 50,00,00,000 I want to show in Indian currency format,in indian format first comma comes after 3 digits then for every 2 digits comma appears.
How to do this ?
I have tried this , but giving an error...
#{
System.Globalization.CultureInfo Indian = new System.Globalization.CultureInfo("hi-IN");
}
#(String.Format(Indian, "{0:N}", modelItem => item.SanctionedAmount))
}
Solved, Thanks to Darin Dimitrov, Answer Is :
#{
var indianCulture = new System.Globalization.CultureInfo("hi-IN");
#string.Format(indianCulture, "{0:N}", item.SanctionedAmount)
}
You seem to have passed some lambda expression to the string.Format function (modelItem => item.SanctionedAmount), but this function doesn't take any delegates.
Try like this:
#{
var indianCulture = new System.Globalization.CultureInfo("hi-IN");
#string.Format(indianCulture, "{0:N}", item.SanctionedAmount)
}
In the same context the following also works if you put in Index.cshtml
<td>#item.Total_Payments.ToString("N")</td>

Backbone.js: Change datetime field from Rails

When I print the created_at field of a model using Backbone.js( <i> {{created_at}} </i>
), I'm getting: 2011-08-07T12:03:00Z.
I'm trying to change the date to a readable format for hours and I'm not being able to.
I want the T and Z to be removed before printing.
thanks
Change the variable in your template context, or add a new one. I would add a new one.
If this is in your render function, it may be changed to something like this:
render: function() {
var context = this.model.toJSON();
context['created_at_formatted'] = this.formatDate(context['created_at']);
var html = this.template.to_html(context);
$(this.el).html(html);
}
With a function added to the view like this:
formatDate: function(d) {
var pad = function (n) {
return n < 10 ? '0' + n : n;
};
// in case the date is a string; you can remove this if you know it will be a date
if (typeof date === 'string') {
d = new Date(d);
}
return [
d.getUTCFullYear(), '-',
pad(d.getUTCMonth() + 1), '-',
pad(d.getUTCDate()), ' ',
pad(d.getUTCHours()), ':',
pad(d.getUTCMinutes()), ':',
pad(d.getUTCSeconds())
].join("");
}
Then the template would be like this:
<i> {{created_at_formatted}} </i>
To simplify the date formatting function, you could also use a date formatting library like DateJS. You could also move the date formatting to the model.
Readable? Why not jQuery timeago?
jQuery timeago
In your Backbone model,
toTemplateData: ->
_.extend
created_duration: do => $.timeago #get("created_at") if #get("created_at")
In your Backbone view,
render: ->
#$el.html(#template(#model.toTemplateData() ))
In your template,
<time title="{{created_duration}}"></time>
You can use the strftime on your created_at
<i> {{created_at.strftime('%Y/%m/%d')}} </i>
Ben's answer is correct but the formatting of the date should really be in a model somewhere as it is business logic.
My variation of that would be:
render: function() {
var context = this.model.format().toJSON();
var html = this.template.to_html(context);
$(this.el).html(html);
}
And in your model, something like:
format() {
this.set('created_at_formatted', formatDate(this.get('created_at')));
return this;
}
formatDate: function(d) {
// format date stuff (See Ben`s answer)
return d;
}
And your template would render:
<i> {{created_at}} </i>
This removes some redundancy, promotes reuse and it is easier to read. Perhaps my answer needs a little work but hopefully you get the general idea.

Resources