Jerry Vermanen
Jerry Vermanen

Reputation: 297

Input field in highcharts graphic

I have a Highcharts graphic http://jsfiddle.net/jerryvermanen/XRjyc/, but I would like to add an input field. The input field asks for a year. After input:

If this is complicated, it could also be done by drawing a new graph after entering a year. This graph would be a step line graph with the same data.

How can this be made?

Upvotes: 1

Views: 2106

Answers (1)

wergeld
wergeld

Reputation: 14442

Interesting requirements and I think I have all of them except for the fifth one. To do this is fairly easy. You need plotLines, input form, and another <div> element.

First you need to pull your year from the input form and add 1 year to it (not sure why +1 but here you go):

passedYear = parseInt($('input:text').val(), 10) + 1;

Then you need to convert this human readable year to a javascript time stamp:

showYear = Date.UTC(passedYear, 0, 1);

From here you also need to take into account if the user inputs a value higher than the max year of the data (and also less than the minimum). Here is how to test for the greater than scenario:

var extremes = chart.xAxis[0].getExtremes();
var maxYear;
maxYear = extremes.dataMax;
if (maxYear > showYear) {
     do stuff
}

You then create your initial plotLine:

    chart.xAxis[0].addPlotLine({
        value: showYear,
        color: 'red',
        width: 2,
        id: 'plotLine'
    });

Next you wanted to show additional plotLine items at 5-year increments:

var plInterval;
plInterval = 5;
    while (nextPL < maxYear) {
        chart.xAxis[0].addPlotLine({
            value: nextPL,
            color: 'red',
            width: 2,
            id: 'plotLine'
        });
        nextYear = nextYear + plInterval;
        nextPL = Date.UTC(nextYear, 0, 1);
    }

This is to assure that we do not add unnecessary plotLine items out to infinity that will never be shown.

Additional requirement was to show "You pay xxxx" text on the page. For this you need a <div> element (or whatever, up to you) to write to. To get the values there is a great function I pulled from here:

function getYValue(chartObj, seriesIndex, xValue) {
    var yValue = null;
    var points = chartObj.series[seriesIndex].points;
    for (var i = 0; i < points.length; i++) {
        if (points[i].x >= xValue) break;
        yValue = points[i].y;
    }
    return yValue;
}

I use it like:

var yVal1;
yVal1 = getYValue(chart, 0, maxYear);
strInterestPay = strInterestPay + yVal1 + '%, ';

I then write this strInterestPay to the <div>:

$("div:interest").html(strInterestPay);

Now, we need to write out the percentages for the additional plotLine items:

yVal1 = getYValue(chart, 0, nextPL);
strInterestPay = ', ' + yVal1 + '%';
$('.content').append(strInterestPay);

DEMO

Upvotes: 2

Related Questions