Nth Fibonacci Term JavaScript *New to JS* - javascript

<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(){
var n = parseInt(n1)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>
I'm new to JavaScript and I've been attempting to construct a code for finding the Nth term of the Fibonacci Sequence where the User inputs a number and the sequence runs until the nth number. I have been tasked with using both a function and a for loop for this. However when I run it, no matter what number I input it returns as 1. My questions is why that might be? I'm a student so I just need general direction not the answer. This snippet is what I have so far.

You weren't capturing the text input value as a parameter.
You had:
checkInput()
It should be
chkInput(n1)
So your line
var n = parseInt(n1);
Was parsing undefined, so the value of n is now NAN (Not a Number), so the for loop never got executed.
function chkInput(n1) {
var n = parseInt(n1);
var a, b, r;
a = 0;
b = 1;
r = 1;
for (var i = 2; i <= n; i++) {
r = a + b;
a = b;
b = r;
}
alert(r);
}
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">

You have almost done with your assignment.
You have missed to receive the value in the function definition.
Altering function chkInput(){ to function chkInput(n1){ will complete your assignment.
Find the your working code snippet below.
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(inputValue) {
var n = parseInt(inputValue)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">
</body>
</html>

You need to get value of element using DOM functions like document.getElementById("n1").value
Also your algorithm is wrong it should have a = 1;
function chkInput(){
var n = parseInt(document.getElementById("n1").value)
var a,b,r;
a = 1;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>

Related

functions inside a class

We need to make a class called Series with two methods
triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15
fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5
Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
addBtns(triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num.value; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
Enter Name <input id="name" placeholder="Enter name"></input>
<button onclick="sayHello()">Click me</button>
<h1 id="hello"></h1>
<input id="num"></input>
<button onclick="tri()">triangular</button>
<div id="feed"></div>
</body>
</html>
You made some mistakes:
you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.
You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .
Same applies for inner function calls, you must access them via this :
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
this.addBtns(this.triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
function start(){
(new Series).tri();
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
<div id="feed"></div>
<input id="num" />
<button onclick="start()">Start</button>
</body>
</html>

javascript - how to use a text box input in a for loop

I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**

How Resolve Currency IDR in javascript

How can resolve script like this ?
for example count or minus Variable A and Variable B in currency IDR
thanks, anyone can help me ...
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
</body>
</html>
here code javascript function :
<script type="text/javascript">
function formatangka_titik()
{
a = form1.harga.value;
b = a.replace(/[^\d]/g,"");
c = "";
panjang = b.length;
j = 0;
for (i = panjang; i > 0; i--)
{
j = j + 1;
if (((j % 3) == 1) && (j != 1))
{
c = b.substr(i-1,1) + "." + c;
} else {
c = b.substr(i-1,1) + c;
}
}
form1.harga.value = c;
</script>
I think your problem is that you are adding two strings together, which will concatenate the strings instead of add the numeric values.
Example adding string types:
var a = '1';
var b = '2';
console.log(a + b); // prints '12' to the console
Example adding int types:
var a = 1;
var b = 2;
console.log(a + b); // prints '3' to the console
JavaScript is loosely typed, so it's not always immediately apparent what a variable's type is.
You can do a few things to change a string-type variable to an int.
Here are a couple common ways:
var stringNum = '123';
var intNum1 = parseInt(stringNum, 10);
var intNum2 = +stringNum;
Specifically, your code would need to look something like this:
function formatangka_titik() {
var a = form1.harga.value.replace(/[^\d]/g, "");
var b = form1.diskon.value.replace(/[^\d]/g, "");
var a = +a; // converts 'a' from a string to an int
var b = +b; // converts 'b' from a string to an int
form1.harga.value = formatNum(a);
form1.diskon.value = formatNum(b);
form1.bayar.value = formatNum(+a + b);
}
function formatNum(rawNum) {
rawNum = "" + rawNum; // converts the given number back to a string
var retNum = "";
var j = 0;
for (var i = rawNum.length; i > 0; i--) {
j++;
if (((j % 3) == 1) && (j != 1))
retNum = rawNum.substr(i - 1, 1) + "." + retNum;
else
retNum = rawNum.substr(i - 1, 1) + retNum;
}
return retNum;
}
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
In above example how we can calculate percentage for IDR currency.

output as undefined/NAN

Would anyone clerify why my program is outputting undefined or NAN? I know for sure that my random number generator is working. Also, I'm trying to sum up all of the "score" value when the number generator has generated the value 10 times. Thanks for the help
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score;
var number;
number = randomnumber()
for (n=0;n<11; n=n+1)
{
if (number==0)
{
score =score+0
}
if (number==2)
{
score =score+2
}
if (number==3)
{
score =score+3
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
Because score variable is undefined. You should initialize it with a number for instance: var score = 0;
Variable score is declared in your totalscore function but never initialised. Adding anything to undefined gives NaN, which is what your function writes to the page.
You need to initialize your score variable with 0. Until you don't, it's value is undefined and when you do math operations on an undefined object, you wil get a NaN error. I have also formatted your code a bit.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
var number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0){
score += 0;
}
else if (number == 2)
{
score += 2;
}
else if (number == 3)
{
score += 3;
}
document.write(score)
}
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
EDIT: If I understand your comment correctly, you should be doing something like this
function totalscore()
{
var n;
var score = 0;
for (n = 0 ; n < 10 ; ++n)
{
score += randomnumber();
document.write(score)
}
var grandTotal = score;
}

random no generate(1-9) using 9 <div> without no repitation,,,,,

I have tried to generate rnadom number(1-9) in 9 div's. How to avoid number repitations? But it's not working, why i cant get output? Thanks in advance.
Here is my code:
<html>
<head>
<title>Random_No</title>
<link rel="stylesheet" type="text/css" href="rno.css">
<script src="rno.js" ></script>
</head>
<body class="outer" onload=random()>
<div id="input1" ></div>
<div id="input2" ></div>
<div id="input3" ></div>
<div id="input4" ></div>
<div id="input5" ></div>
<div id="input6" ></div>
<div id="input7" ></div>
<div id="input8" ></div>
<div id="input9" ></div>
<script>
function random()
{
var a=new Array("input1","input2","input3","input4","input5","input6","input7","input8","input9");
x=a.length;
var ran=new Array();
for(var i=0;i<x;i++)
{
ran[i]=Math.floor(Math.random()*9);
}
for(var i=0 ; i<x ; i++)
{
document.getElementById("a[i]").innerHTML=ran[i];
}
}
</script>
</body>
</html>
Replace
document.getElementById("a[i]").innerHTML=ran[i];
By
document.getElementById(a[i]).innerHTML=ran[i];
And... why 2 loops ?
Because you only want a small set of items randomised with no repeats and to take each one, a Fisher-Yates shuffle would be very efficient here.
var inputs = [], i;
for (i = 1; i < 10; ++i) // get each input
inputs.push(document.getElementById('input' + i));
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
inputs = shuffleArray(inputs); // shuffle
for (i = 0; i < 9; ++i) // give values (already shuffled)
inputs[i] = i + 1; // there will be no repeats because we're counting up
Another way to generate randoms from a set-
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Random_No</title>
</head>
<body >
<div id= "input1"></div>
<div id= "input2"></div>
<div id= "input3"></div>
<div id= "input4"></div>
<div id= "input5"></div>
<div id= "input6"></div>
<div id= "input7"></div>
<div id= "input8"></div>
<div id= "input9"></div>
<script>
function random_no(){
var i=0, ran=[1,2,3,4,5,6,7,8,9];
while(i<9){
document.getElementById("input"+(++i)).innerHTML=
ran.splice(Math.floor(Math.random()*ran.length),1);
}
}
onload=random_no;
</script>
</body>
</html>
You need to change
document.getElementById("a[i]").innerHTML = ran[i];
to
document.getElementById(a[i]).innerHTML = ran[i];
because putting quotes around a[i] makes it look for an element whose id is actually "a[i]"
You can map the elements in another array, shuffle it and inject the random number in basically one chained operation using some array methods:
var divs = document.getElementsByTagName('div');
[].map.call(divs, function(e, i) {
return i;
}).sort(function() {
return (Math.round(Math.random())-0.5);
}).forEach(function(r, i) {
divs[i].innerHTML = r;
});
DEMO: http://jsfiddle.net/EsGL3/
You can use Array.sort() with a random comparator to re-order the values:
JSFIDDLE
function random()
{
var x = 9,
ids = [ 'input1', 'input2', 'input3',
'input4', 'input5', 'input6',
'input7', 'input8', 'input9'
],
values = [1,2,3,4,5,6,7,8,9],
i = 0;
Array.sort( values, function(a,b){ return Math.random() < 0.5 ? 1 : -1; });
for( ; i < x; ++i)
{
document.getElementById( ids[i] ).innerHTML = values[i];
}
}

Categories

Resources