<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--;
}
}
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.