Fibonacci

by Thomas Orthbandt

HTML

<h2>jQuery script to print Fibonacci series</h2>
<h3>Enter the value:</h3>
<input type="text" id="value" />
<button id="getfibonacci">Print Fibonacci Series</button>
<!-- output div -->
<h4>Output: <span id="output"></span></h4>

JavaScript

$(function() {
  $('#getfibonacci').click(function() {
    //define variables
    var first_num = 1,
      second_num = 1,
      next_num,
      outputdiv;

    //get the value from textbox
    var value = $('#value').val();

    //set output div object to the variable 'outputdiv'
    var outputdiv = $('#output');

    //check if the input is not empty
    if (value == '') {
      outputdiv.html('<br>Please enter a value');
      return;
    }
    //check if the value should be more than 1
    if (value < 2) {
      outputdiv.html('<br>Enter value more than 1');
      return;
    } else {
      //clear the div
      outputdiv.html('');

      //print first two number 0 and 1
      outputdiv.append('<br>' + first_num);
      outputdiv.append('<br>' + second_num);

      //loop through the value till it becomes 0 (zero)
      while (value > 2) {
        //add the first value and second to get the next value
        next_num = first_num + second_num;

        //assign second value to first
        //next value to second to find the next series
        first_num = second_num;
        second_num = next_num;

        //print the next value
        outputdiv.append('<br>' + next_num);

        //decrement the value by one 
        value--;
      }
    }
  });
});