JSFiddle - React, Tailwind, and code Playground
by Ty
HTML
Fibonacci Solution - HTML
<!-- RocketU Bootcamp Exercise solution Topic: JavaScript Filename: fibonnaci.html Overview: Solution to exercise 4 in JavaScript deck Related files: functions3.js -->
<!DOCTYPE html>
<title>JavaScript Exercise Fibonacci</title>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid #ccc;
padding: 2px;
}
</style>
<body>
<h1>JavaScript Exercise Fibonacci </h1>
<label>Number of values:
<input type="text" id="numvals">
</label>
<label>
<input type="radio" name="output" value="console">Console</label>
<label>
<input type="radio" name="output" value="table">Table</label>
<button onclick="getInput();">Print Fibonacci Values</button>
<!-- Placeholder div to insert table HTML if required -->
<div id="fibtable"></div>
</body>
</html>
CSS
body {
font-family: Verdana;
color: Grey;
text-align: center;
background-image: url( "http://rlv.zcache.com/doge_very_wow_much_dog_such_shiba_shibe_inu_mousepad-r9af8466ffba24bc283cb904077931203_x74vi_8byvr_324.jpg")
}
h1 {
color: red;
}
button {
color: white;
background: black;
font-weight: bold;
}
JavaScript
/**
* @file functions3.js
* @author Nick Roper <[email protected]>
* @overview Solution to exercise 4 in JavaScript deck
* @copyright RocketSpace Inc.
* @version 1.0
*/
function getFibonacciArray(num) {
var myArray = [];
for (var i = 0; i < num; i++) {
if (i === 0) {
myArray.push(0);
} else if (i === 1) {
myArray.push(1);
} else if (i > 1) {
myArray.push(myArray[i - 2] + myArray[i - 1]);
}
}
return myArray
}
function getInput() {
// Declare variables
var fibCount, // Number of values required
outputType, // Type of output (console or table)
radios; // Selection of radio buttons on th epage
// Test the value entered
// If no value is entered value will be an empty string ("")
// Input should be tested as numeric
fibCount = document.getElementById("numvals").value;
// Not an empty string or null or Not a Number
if (fibCount == "" || isNaN(fibCount)) {
// Display message and then exit the function (return);
alert("Invalid entry!");
return;
} else {
// Input is OK - cast to an integer
fibCount = parseInt(fibCount);
var theFibArray = getFibonacciArray(fibCount);
}
// Now test the radio button
// We need to do this with a loop in vanilla JavaScript
// Much easier with jQuery!
radios = document.getElementsByName('output');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
outputType = radios[i].value;
// only one radio can logically be checked, don't check the rest
break;
}
}
if (outputType == "console" || outputType == "table") {
displayFibonacciOutput(fibCount, outputType);
} else {
// Display message and then exit the function (return);
alert("Please select an output...