javascript document.getElementById Loop - javascript

I am trying to make this print out the grades in the array that I created. I can get my for loop to cycle through all of the grades in the array but it only prints out the last grade. I have it set up to print the grade out each time the for loop completes one cycle, but as I said, it is only printing out the last grade. I also tried to use the .innerHTML but that did not work either as you will see in the code:
var arrayTest = [78, 65, 41, 99, 100, 81];
var arrayLength = arrayTest.length;
var midtermTest = 60;
var msg = "";
var grade;
arrayOfGrades();
addBonus();
function tellGrade() {
if (grade > 100) {
msg = "Grade is higher than 100!, " + grade;
}
else if (grade >= 90) {
msg = "You got an A " + grade + "!!, ";
}
else if (grade >= 80) {
msg = "You got a B " + grade + "!!, ";
}
else if (grade >= 70) {
msg = "You got a C " + grade + "!!, ";
}
else if (grade >= 60) {
msg = "You got a D " + grade + "!!, ";
}
else if (grade <= 59) {
msg = "You got a F " + grade + "!! :(, ";
}
else if (grade < 0) {
msg = "Grade is less than 0, " + grade;
}
}
function arrayOfGrades() {
for (var i = 0; i < arrayLength; i++) {
grade = arrayTest[i];
tellGrade(grade);
writeGrade();
}
}
function addBonus()
{
midtermTest = midtermTest + (midtermTest * .05);
grade = midtermTest;
tellGrade(grade);
writeMidtermGrade();
}
function writeGrade() {
//document.getElementById("test").innerHTML = "Test grade letter: " + msg.toString() + "<br />";
var el = document.getElementById('test');
el.textContent = "Test grade letter: " + msg.toString();
}
function writeMidtermGrade() {
var el = document.getElementById('midterm');
el.textContent = "Midterm test grade letter: " + msg.toString();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DecisionsAndLoopsAssignment1_Byrd</title>
<link href="css/default.css" rel="stylesheet" />
</head>
<body>
<div id="test">Missing grade!!</div>
<div id="midterm">Missing grade!!</div>
<script src="js/main.js"></script>
</body>
</html>

function writeGrade() overwrites whatever might already by in the elements it outputs to. So when called more than once only the last value is preserved. Using .innerHTML would do the same thing. Accumulating the content strings to a single var then making a single call to output them is one option to fix this.
I also note that you're passing temporary values around in global vars, which is generally considered poor form.

You are setting the ENTIRE content of the element not just adding on to it. This will constantly overwrite the work of the previous iteration of the loop, therefore you will only see the last result, cause computers are fast.
You have two options, read the textContent of the element, and continue adding to it. This concept is called self assignment.
var aMessage = "Hello, ";
aMessage += "World!";
console.log(aMessage") // => "Hello, World!"
Though general we would create a new element and append that element as a child
var msg = "A+"; // this should be a variable to our function vs a global va
function writeGrade() {
var el = document.getElementById('test');
var newEl = document.createElement("p");
newEl.textContent = "Test grade letter: " + msg.toString();
el.appendChild(newEl)
}
writeGrade()
<div id="test">
</div>

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

Problem in executing the complete javascript

The program is not running and just showing blank window when opened in browser. Please help me found the issue with the code why it is not executing You need to create a program that will display flight information to a person. The program will continue to provide
information to the user until they indicate that they are no longer interested in searching (they will enter Q or X to stop).
The user will be prompted to enter a city to search for and you will look for any flight that starts in this city and display
the information associated with that flight.
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = [RE103, RE305, RE307, RE309];
pricePerPerson = [110, 75, 90, 120];
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
</body>
</html>
Looks like you forgot the quote in your array with string and numbers combined in the following line:
flightNumber = [RE103, RE305, RE307, RE309];
Shouldn't it look like this:
flightNumber = ["RE103", "RE305", "RE307", "RE309"];
Consider the following.
/*
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = ["RE103", "RE305", "RE307", "RE309"];
pricePerPerson = [110, 75, 90, 120];
*/
// Prepare data
var flights = [{
flightNumber: "RE103",
city: {
start: "Atlanta",
finish: "Cleveland"
},
pricePerPerson: 110
}, {
flightNumber: "RE305",
city: {
start: "Cleveland",
finish: "Indianapolis"
},
pricePerPerson: 75
}, {
flightNumber: "RE307",
city: {
start: "Indianapolis",
finish: "Louisville"
},
pricePerPerson: 90
}, {
flightNumber: "RE309",
city: {
start: "Louisville",
finish: "Atlanta"
},
pricePerPerson: 120
}];
$(function() {
// Define Functions
function getFlightDataByNumber(flightNumber, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.flightNumber.toLowerCase() == flightNumber.toLowerCase()) {
results = flight;
}
});
return results;
}
function getFlightDataByStart(cityName, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.city.start.toLowerCase() == cityName.toLowerCase()) {
results = flight;
}
});
return results;
}
function promptForFlight() {
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
var myFlight = getFlightDataByStart(inputString, flights);
if (myFlight !== false) {
$("#idSpan").show();
$("<ul>", {
class: "flightData"
}).insertAfter("#idSpan");
$("<li>").html("<label>Flight Information:</label>").appendTo(".flightData");
$("<li>").html("<label class='fixed'>Departs:</label>" + myFlight.city.start).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Arrives:</label>" + myFlight.city.finish).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Number:</label>" + myFlight.flightNumber).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Cost:</label>$" + myFlight.pricePerPerson.toFixed(2)).appendTo(".flightData");
}
}
}
// Run Code
promptForFlight();
});
/*
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
*/
.flightData {
margin: 0;
padding: 0;
list-style: none;
}
.flightData li label {
font-weight: bold;
display: inline-block;
}
.flightData li label.fixed {
width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
Instead of using multiple unique Arrays, you may want to use an Array of Objects. This will help create a relationship between the various elements. Once you have identified the one object you need, you can easily access all the other related details.
Based on your code, you are asking the User to enter a City name, yet this is not explained well in your Prompt. You should consider clarifying the prompt better or using another Input method.
Once we have the User input, we can use the function to seek out the proper object, if we do not find it, false is returned. You have no feedback to the User if the Flight cannot be found. You might consider that scenario further.

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

How do I make a document wait for an assigned input value?

I am writing a number guessing game. Every time I run the document it automatically goes to my outer else statement and I know why, but I can't figure out how to make it wait for an input value of the textbox. I want to set "guess" = to the value of the text box by pressing submit which will then enter the if statements. At the moment it is automatically setting to null and causing the error. Here is the code.
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
Have you tried to disable the button, then add an onChange event to your text box so that you can enable the button once you have the desired input? You will need to add an ID or Name value to your button so it can be accessed? And to add what #LGSon added:
if(myguess <= last && myguess >= first && cont == true){, you check the variable cont, which I can't find in your code, so if it is not declared and set somewhere, you code will always take the outer route.
Second, you need to split your search function into 2 functions, one that generates the input, one that runs when someone entered a value (which can be fired on keypress or with a button)

Javascript Guessing Game

I'm brand new to javascript and html so I was hoping someone could peek at my code and tell me why certain syntax isn't working. In the code below I use document.getElementById to retreive the element I'd like to work with each time. I do declare them as local variables within gameTime() and use it throughout the function.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
function gameTime()
{
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
document.getElementById("guess").value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
document.getElementById("guess").value = "";
document.getElementById("status").value = "";
}
function quit()
{
document.getElementById("status").value += ("The correct number was " + randNum + "!\r")
}
Then I tried it by globally declaring the two elements and use it in every function which does not seem to work at all and I just don't understand why.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
function gameTime()
{
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
guess.value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
guess.value = "";
status.value = "";
}
function quit()
{
status.value += ("The correct number was " + randNum + "!\r")
}
And here's the html file that accompanies these js files guess.js is the first code block, guessAgain.js is the second code block.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" src="guessAgain.js"></script>
</head>
<body>
<label for = "guess"> Your Guess: </label>
<input type = "text" id = "guess" value = "" />
<input type = "button" onclick = "gameTime()" value = "Submit" />
<input type = "button" onclick = "reset()" value = "New Game" />
<input type = "button" onclick = "quit()" value = "Quit" />
<br>
<textarea id = "status" rows = "10" cols = "52"></textarea>
</body>
</html>
Thanks for any insight you can give me.
Issue 1:
You are calling the following before the body loads and hence, they return undefined.
var guess = document.getElementById("guess");
var status = document.getElementById("status");
You should do these only after the body loads on the onload() event.
Issue 2:
Also, when you assign the value itself to a variable, it isn't updated as the textbox is. var guess = document.getElementById("guess").value, then guess's value does not get updated if you change the textbox.
If you refer to var guess = document.getElementById("guess"), then, repeatedly calling
guess.value will return the latest value of the input field.
(Working Example)
The following is not wrong by unnecessarily complicated.
numGuesses++;
if(guess.value == "")
{
alert("You did not guess a number!")
numGuesses--;
}
...
Instead, you could increment numGuesses once it is deemed a valid guess, i.e. at the end.
You're setting guess to element.value
It should be
var guess = document.getElementById("guess");
Problem is that you're using guess as an element here:
guess.value = "";
You'll also need to modify places where you use guess as a string into guess.value.

Categories

Resources