output as undefined/NAN - javascript

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;
}

Related

What is missing from my discount code to make this work? Am I missing a variable?

I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase =
parseInt(document.getElementById('purchase').value);
var dayOfWeek = new Date().getDay();
var output = document.querySelector("#output");
let rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
let discount = purchase * rate;
return purchase - discount;
output.innerHTML = "$" + String(getDiscountedAmount(200));
}
</script>
Please enter your final price: <input type="text" id="purchase" size="5">
<br>
<button type="button" onclick="getDiscountedAmount(purchase)">discount?
</button>
<div id="output"></div>
</body>
</html>
The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function
var purchase = parseFloat();
Try:
purchase = parseFloat(purchase);
so that it uses your input parameter.
Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)
And lastly your function returns a value but then you don't see that value anywhere, try using
console.log(getDiscountedAmount(200)) or whatever your price is
In terms of your input and output you want to use DOM manipulation to get the input and show the output.
If you want to see the value in your "output" then
var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));
Would be a simple DOM mechanism, but it's not the cleanest
One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them
Altogether a cleaner version of your code:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
Please enter your final price: <input type="text" id="myInput" size="5" /><br />
<button type="button" id="myButton">discount?</button>
<div id="myOutput"></div>
<script>
var myInput = document.querySelector("#myInput");
var myOutput = document.querySelector("#myOutput");
var myButton = document.querySelector("#myButton");
myButton.onclick = function() {
// Computes and returns a discounted purchase amount.
var purchase = parseFloat(myInput.value);
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 1000) {
rate = 0.025;
} else {
rate = 0.03;
}
let discount = purchase * rate;
var finalPrice = purchase - discount;
output.innerHTML = "$" + String(finalPrice);
};
</script>
</body>
</html>
I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS
When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.
In your first line of the function you are using parseFloat(); wrong:
var purchase = parseFloat();
Do:
var purchase = parseFloat(purchase);
Than you need to get your input number.
getDiscountedAmount(purchase) in the onclick event doesn't work.
You can use this:
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
In the end you have to do this to show the number in you output div:
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
Here is your code and how i fixed it:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
}
else if (purchase < 100 && dayOfWeek ==(2,3)) {
rate = 0.06;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
}
</script>
</head>
<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>
<button type="button" onclick="getDiscountedAmount()">discount?</button>
<div id="output"></div>
</body>
</html>
I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.
Here is what you are looking for:
body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}#media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<div class='wrapper'>
<div class='content'>
<label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
<button type="button" onclick="getDiscountedAmount()">See discount</button>
<div class='output-container'>Total: <span id='output'>--</span></div>
</div>
</div>
<script>
//Get the output element
outputEl = document.getElementById("output");
function getDiscountedAmount() {
//Gets the value of your input
var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
//Checks if output is a number.
if(isNaN(output)){
output = 'Not a number!';
} else{
output = '$' + output;
}
//Puts the output inside of your "output" <div>
outputEl.textContent = output;
}
</script>
</body>
</html>

JavaScript If Else errors

So I have this little problem with my if else structure. When I put in a correct star for example "Vega", the costellation shows me that it is false ("Error") while it needs to show me "Lyra".
My code is below:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
The problem is, when the for loop is running, the test.inputConstellations.value will be overridden, even if previously the program found a match. The solution is the break:
if(test.inputStars.value==stars[n]){
test.inputConstellations.value=constellations[n]
break
}else{
test.inputCostellations.value = "Error"
}
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break
}else{
test.inputCostellations.value = "Error";
}
}
}
<!DOCTYPE html>
<html>
<head>
<title> Array structures</title>
</head>
<body>
<form name = "test">
<input type = "text" name = "inputStars">
<input type = "button" onclick ="Arrays()" value = "Find costellation">
<input type = "text" name = "inputCostellations">
</form>
</body>
</html>
You can set a default value for variable and overwrite when true:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
}
}
}
And use a break:
var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
test.inputCostellations.value = "Error";
for (n = 0; n < 7; ++n) {
if (test.inputStars.value == stars[n]) {
test.inputCostellations.value = costellations[n];
break;
}
}
}

Javascript not allowing for static variable to be updated each time on click

I am trying to make it where when the user clicks the demo section toggles the flag value each time.
I was under the impression that the static variable was myFunction.flag and it would remain constant throughout the page each time it changes...
<!DOCTYPE html>
<html>
<body>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
myFunction.flag = 1;
if(myFunction.flag){
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 0;
} else {
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 1;
}
}
</script>
</body>
</html>
You are creating a new variable each time a click happen.
Just make it global.
<script>
var flag = 0;
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
if(flag){
document.getElementById("demo").innerHTML = myFunction.flag;
flag = 0;
} else {
document.getElementById("demo").innerHTML = myFunction.flag;
flag = 1;
}
}
</script>

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>**

Making a javascript hangman game and I can't get my function to apply to repeated letters

Everything about the script works great right now unless there's a repeated letter in the word. If so, then it will only display the first of the letters. For example, if the random word is "look" it would display like this "lo k".
Unfortunately the only other related javascript hangman question here was for a script that didn't actually have issues on repeated letters. For reference: how to deal with repeated letters in a javascript hangman game. Can anyone help me get through the repeated letter issue? Thanks!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-1.11.2.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<link rel="stylesheet" href="css/main.css">
<title>Hang a Blue Devil</title>
</head>
<body>
<div class="wrapper">
<h1 class="title">Hangman</h1>
<h2 class="attempt-title">You have this many attempts left: </h2>
<ul class="hangman-word">
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
</ul>
<h3 class="hangman-letters"></h3>
<input class="text-value" type="text" maxlength="1" onchange="setGuess(this.value)">
<button class="text-button" onclick="checkGuess()"></button>
<p class="letters-guessed"></p>
</div>
</body>
<script src="js/hangman.js"></script>
</html>
My JS:
var hangmanWords = [
"the","of","and","a","to","in","is","you","that","it","he",
"was","for","on","are","as","with","his","they","I","at","be",
"this","have","from","or","one","had","by","word","but","not",
"what","all","were","we","when","your","can","said","there",
"use","an","each","which","she","do","how","their","if","will",
"up","other","about","out","many","then","them","these","so",
"some","her","would","make","like","him","into","time","has",
"look","two","more","write","go","see","number","no","way",
"could","people","my","than","first","water","been","call",
"who","oil","its","now","find","long","down","day","did","get",
"come","made","may","part"
];
// declared variables
var randomNumber = Math.floor(Math.random() * 100);
var randomWord = hangmanWords[randomNumber];
var underscoreCount = randomWord.length;
var underscoreArr = [];
var counter = randomWord.length +3;
var numberTest = 0;
var lettersGuessedArr = [];
var lettersGuessedClass = document.querySelector('.letters-guessed');
var li = document.getElementsByClassName('tester');
var textValue = document.querySelector('.text-value');
var attemptTitle = document.querySelector('.attempt-title');
var hangmanWordClass = document.querySelector('.hangman-word');
var hangmanLettersClass = document.querySelector('.hangman-letters');
// actions
attemptTitle.innerHTML = "You have this many attempts left: " + counter;
console.log(randomWord);
function setGuess(guess) {
personGuess = guess;
}
for (i=0;i<underscoreCount;i+=1) {
underscoreArr.push("_ ");
underscoreArr.join(" ");
var underscoreArrString = underscoreArr.toString();
var underscoreArrEdited = underscoreArrString.replace(/,/g," ");
hangmanLettersClass.innerHTML = underscoreArrEdited;
}
function pushGuess () {
lettersGuessedArr.push(personGuess);
var lettersGuessedArrString = lettersGuessedArr.toString();
var lettersGuessedArrEdited = lettersGuessedArrString.replace(/,/g," ");
lettersGuessedClass.innerHTML = lettersGuessedArrEdited;
}
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
i += 20;
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
};
My bin:
http://jsbin.com/dawewiyipe/4/edit
You had a stray bit of code that didn't belong:
i += 20;
I took it out, and the problem went away (the loop was intended to check each character, the +=20 broke the process of checking each character)
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
}
http://jsbin.com/noxiqefaji/1/edit

Categories

Resources