Domanda

I try to define a custom date parser for jquery plugin. Here is my table : table using jquery tablsorter plugin

I've tried to define a custom date parser in my jQuery like this :

<script type="text/javascript" src="{% static 'js/jquery.tablesorter.min.js' %}"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('.tablesorter').tablesorter();

         // add parser through the tablesorter addParser method 
        $.tablesorter.addParser({
            id: "customDate",
            is: function(s) {
                return /[0-9]{1,2} [a-zA-Z]+, [0-9]{1,2}:[0-9]{1,2}/.test(s);
                //return false
            },
            format: function(s) {
                s = s.replace(/,/,"").replace(/:/," ");
                s = s.replace(/January/,1).replace(/February/,2).replace(/March/,3).replace(/April/,4).replace(/May/,5).replace(/June/,6).replace(/Jully/,7).replace(/August/,8).replace(/September/,9).replace(/October/,10).replace(/November/,11).replace(/December/,12);
                s = s.split(" ");
                s = s[1]*1000000+s[0]*10000+s[2]*100+s[3]
                return s
            },
            type: "numeric"
        });
    });

</script>

But it doesn't work. It looks like the customDate parser is not called at all. The Date field is only sorted by the first number (the day of the date).

It's the first time I define a custom parser. I've readed those subject to do it :

http://tablesorter.com/docs/example-parsers.html

date Sorting Problem with Jquery Tablesorter

È stato utile?

Soluzione

I fixed it. My mistake was to use the $.tablesorter.addParser inside the $(document).ready(function() function...

I just did it this way :

        $.tablesorter.addParser({
        id: "customDate",
        is: function(s) {
            return /^[0-9]{1,2} [a-zA-Z]+, [0-9]{1,2}:[0-9]{1,2}$/.test(s);
        },
        format: function(s) {
            s = s.replace(/,/,"").replace(/:/," ");
            s = s.replace(/January/,1).replace(/February/,2).replace(/March/,3).replace(/April/,4).replace(/May/,5).replace(/June/,6).replace(/Jully/,7).replace(/August/,8).replace(/September/,9).replace(/October/,10).replace(/November/,11).replace(/December/,12);
            s = s.split(" ");
            s = s[1]*1000000+s[0]*10000+s[2]*100+s[3];
            return s;
        },
        type: "numeric"
    });

    $(document).ready(function() {
        $('.tablesorter').tablesorter({ 
            headers: { 
                1: { 
                    sorter:'customDate' 
                } 
            } 
        }); 

    });

and now it's working correctly !

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top