klaaz
klaaz

Reputation: 551

jQuery Flot fails to show chart data

I am using the great chart plugin Flot to replace strings in a html page to a charts. However, somehow the plot itself is not showing.

The placeholders:

<div class="chart" id="example1" style="width:300px; height:150px">2009:12.90,2010:12.80,2011:13.90,2012:14.50</div>
<div class="chart" id="example2" style="width:300px;height:150px">1:2,2:1,3:6,4:3</div>

Th jQuery code:

$(".chart").each(function(index, value) {

    var id = this.id;

    var obj = $("#" + id).html().split(",");
    var chartdata = [];

    $.each(obj, function(i, val) {
         chartdata[i] = "[" + val.replace(":","," ) + "]";
         console.log(val);
    });

    var thechart = chartdata.join(",");
    console.log(thechart);

    var d1 = "[" + thechart + "]";
    console.log("#" + id + " -> " + d1);

    $.plot($("#" + id), [
        {
            data: d1,
            lines: { show: true, fill: true }
        },
    ]);

 });

When I replace d1 with the actual data it works. I suspect it has something to do with the data being presented as strings or something. Can't get it right though. I don't want to add the data into the jquery call because I us a cms so the user can change the chart data while editing the page.

Upvotes: 0

Views: 295

Answers (1)

DNS
DNS

Reputation: 38219

Yes, it's because you're creating your data as a big string, not an array of values. Taking this line as an example:

chartdata[i] = "[" + val.replace(":","," ) + "]";

You should instead be using code (roughly) like this:

values = val.split(":");
chartdata[i] = [parseInt(values[0]), parseInt(values[1])];

Most of the rest of your code is then unnecessary; obj is already a list.

You could make the whole thing simpler by using jQuery's 'map' instead of 'each'; then you wouldn't even need the separate chartdata variable; roughly (untested) like this:

$(".chart").each(function() {

    var id = this.id;
    var data = $("#" + id).html().split(",");

    $.map(data, function(point) {
        return $.map(point.split(":"), function(value) {
            return parseInt(value);
        });
    });

    $.plot("#" + id, [{
        data: data,
        lines: {
            show: true,
            fill: true
        }
    }]);
});

Upvotes: 1

Related Questions