Passing an input variable to a function


I’m using Keith Wood’s jquery plugin to produce some graphs for my site. Though I’ve been able to produce “static” ones, I’d like the user to be able to input a new constant and then have my graph update it according to what they enter. I’m not quite sure how to add the value that the user inputs to my linear function below. So far I have:

<input type="text" size="1" id="plotit2" name="plotit2"/>

for the user to input the desired change. Then I have:

$('#plotIt1').click(function() {
	var svg = $('#svgplot').svg('get');
	svg.plot.noDraw().addFunction('lingraph', linear, 'blue', 3).redraw();

where the “linear function” successfully prints out a static graph when the user hits submit. But then to produce a different graph when the user changes the input (via #plotit2) instead, I have my questionable code (hence the question marks!) below:

// Produce linear graph
function linear(x) {
	return x+????;  //I need to be able to somehow get my input value here

I’ve parsed down the code to what I think are the important points but if I can clarify anything I’d be happy to do so.

Thanks for your help.


You could pass the value to a function, and then from that function return the linear function you require. That returned function will retain knowledge of your value.

function linearWithOffset(offset) {
    return function (x) {
        return x + offset;

You could then make use of it with something like:

var offset = $('#plotIt2').attr('value');
svg.plot.noDraw().addFunction('lingraph', linearWithOffset(offset), 'blue', 3).redraw();

Thanks Paul! I’m sure that I’m going to use that technique in the future as well.