I solved the issue. The test cases kept on failing probably because there was a try catch block that needed to be implemented. I completely forgot about that. The test cases worked when I added the try catch block. Thanks for all the suggestions. Problem Statement: I need to design a simple html form that takes a limit as input and displays the first given number of the Fibonacci series. for eg. if 5 is given as input it displays: 0 1 1 2 3 if 8 is given as input it displays: 0 1 1 2 3 5 8 13 But I keep on getting this error:
testFiboForNonZeroPositiveInput:
Check for the logic and check if the correct output is displayed in div with id 'result'
testFiboForZeroInput:
Check for the logic and check if the correct output is displayed in div with id 'result'
TEST CASE FAILED
Here is my code:
function getFibonacci(){
var fib=document.getElementById("fibo").value;
var text;
var arr=[];
if (fib.length===0){
text="Please, specify a number.";
document.getElementById("result").innerHTML = text;
}
else if (fib<0){
text="Please, specify a positive number.";
document.getElementById("result").innerHTML = text;
}
else{
var n1 = 0, n2 = 1, nextTerm, i;
for (i = 1; i <= fib; i ) {
arr.push(n1);
nextTerm = n1 n2;
n1 = n2;
n2 = nextTerm;
}
var newStr = arr.join(' ').trim()
document.getElementById("result").innerHTML=newStr;
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
<script src="script.js"></script>
</head>
<body>
<form onsubmit=" return getFibonacci()">
<label for="Enter the number to get a fibonacci">Enter the number to get a fibonacci</label>
<input type="number" id="fibo" name="fibo"><br>
<input type="submit" value="Get Fibonacci Numbers" id="fibobtn">
<div id="result"></div>
</form>
</body>
</html>
Everything seems to work fine and I get the Fibonacci series and the other messages as required but my test cases fail due to this error. Please tell me what to do to fix this issue.
CodePudding user response:
I made these changes to the code and the test cases worked: (Added a required try catch block)
function getFibonacci(){
try{
var fib=document.getElementById("fibo").value;
var text;
var arr=[];
if (fib.length===0){
text="Please, specify a number.";
document.getElementById("result").innerHTML = text;
}
else if (fib<0){
text="Please, specify a positive number.";
document.getElementById("result").innerHTML = text;
}
else if(fib>0){
var num1=0;
var num2=1;
var nextterm;
var i=0;
for (i = 0; i < fib; i )
{
arr.push(num1);
nextterm=num1 num2;
num1=num2;
num2=nextterm;
}
var newStr = arr.join(' ');
document.getElementById("result").innerHTML=newStr;
}else {
text="0";
document.getElementById("result").innerHTML = text;
}
}
catch(err){
document.getElementById("result").innerHTML=err;
}
return false;
}
CodePudding user response:
A for
attribute on label
must by referencing to an id.
<input type="number" id="fibo" name="fibo">
<label for="fibo">Enter the number to get a fibonacci</label>