1

I am trying to write a code in javascript/jquery and html which I thought would be fairly simple, but turns out to be quite challenging (to me). I have a program which computes the first x numbers of the fibonacci sequence, and stores it in an array. What I am trying to do is make two buttons that will display the next or previous number in the sequence. This is what I have so far.

Javascript:

var all = new Array();
fib = function (numMax) {
    for (i = 0, j = 1, k = 0; k < numMax; i = j, j = x, k++) {
        x = i + j;
        //window.document.write(x + " ");
        all[k] = x;
    }
};

fib(1000);

fibon = function () {
    getElementById("mynum").innerHTML = "all[+1]";
};

HTML:

<input type="text" id="mynum">
<button onclick="fibon();">Next</button>

1 Answer 1

5

You need a variable that contains the current index, and then increment it each time you click.

fibindex = 0;

function fibon() {
    if (fibindex >= all.count) {
        document.getElementById("mynum").value = "We've run out of Fibonacci numbers";
    } else {
        document.getElementById("mynum").value = all[fibindex];
        fibindex++;
    }
}

Also, notice that you should not put quotes around a use of a variable. Add you use .value to fill in an input, not .innerHTML.

DEMO

Sign up to request clarification or add additional context in comments.

6 Comments

Was just about to add that when you wrote.
Could you make a jsfiddle please?
How would I add a button to display the previous number?
Exactly the same, except you decrement the index instead of incrementing it.
And use 0 as the bound test, instead of all.count, of course.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.