This is an another interesting topic for the school and college students, In this post you are going to learn how to write a jQuery script to print Fibonacci series, this kind of programs usually people write in server side or console scripts like C, JAVA, PHP, ASP, JSP etc., but I have written in jQuery, so the beginners can understand the basics of jQuery.
What you will learn from this jQuery Fibonacci script?
1. To get the value of a textbox using val() jQuery function.
2. To print the value to a HTML DIV element in jQuery using html() function.
3. To append the value to a HTML DIV using jQuery append() function.
4. While loop in jQuery (there is no difference from traditional JavaScript).
5. Adding two number in jQuery (no difference from JavaScript).
6. IF condition (same as JavaScript)
Here is the entire HTML & jQuery script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<!DOCTYPE html> <html> <head> <title>jQuery Fibonacci Script</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function(){ $( '#getfibonacci' ).click( function(){ //define variables var first_num = 0, second_num = 1, next_num, outputdiv; //get the value from textbox var limit = $( '#limit' ).val(); //set output div object to the variable 'outputdiv' outputdiv = $( '#output' ); //check if the input is not empty if(limit == ''){ outputdiv.html( '<br>Please enter a value' ); return; } //check if the limit should be more than 1 if(limit < 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 limit till it becomes 0 (zero) while( limit > 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 limit by one limit--; } } }); }); </script> </head> <body> <h2>jQuery script to print Fibonacci series</h2> <h3>Enter the limit:</h3> <input type="text" id="limit" /> <button id="getfibonacci" >Print Fibonacci Series</button> <!-- output div --> <h4>Output: <span id="output"></span></h4> </body> </html> |
Read the comments in the above script to understand it.
And finally as always, here is the demo:
Enjoy the day. Like this website in Facebook to get updates. Good Luck!.