Number Guessing Game using while loop - javascript

In this project, I need to set a maximum of 10 guesses, an indication of what number is being guessed and keep those results on the screen at the end of each game without overwrite the previous guesses.
Each set of guess output needs to be numbered to indicate how many guesses have been made. For the output, I need to use innerHTML. The user will guess a number from 1 to 999. I have to use while loop.
So far this is the code where I'm working and I have some errors and it's not working. Can anybody put me in the right direction to finish this code?
The errors that I found when I inspect the document are checkGuess() function and an anonymous function with a message "Cannot read property 'value' of null"
<script type="text/javascript">
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.getElementById("guesses");
var lastResult = document.getElementById("lastResult");
var lowOrHi = document.getElementById("lowOrHi");
var guessSubmit = document.getElementById("guessSubmit");
var guessField = document.getElementById("guessField");
var guessCount = 1;
function checkGuess() {
var userGuess = Number(guessField.value);
guesses.innerHTML += userGuess + "";
}
while (guessCount == 10) {
lastResult.innerHTML = "!!!GAME OVER!!!";
disableForm();
} else {
if (userGuess == randomNumber) {
lastResult.innerHTML = "Congratulations! You got it right!";
lowOrHi.innerHTML = "";
disableForm();
} else {
lastResult.innerHTML = "Wrong!";
if (userGuess < randomNumber) {
lowOrHi.innerHTML = "Your guess is too low!";
} else if (userGuess > randomNumber) {
lowOrHi.innerHTML = "Your guess is too high!";
}
}
guessCount++;
guessField.value = "";
}
}
function disableForm() {
var wholeForm = document.querySelector(".form"); // grab a reference to the whole form (the contents of the div with class form)
wholeForm.style.opacity = 0.5; // change the opacity of the form to 0.5
guessField.setAttribute("disabled", "disabled");
guessSubmit.setAttribute("disabled", "disabled"); // disable the form field and submit button so they can no longer be used
}
guessSubmit.onclick = checkGuess;
</script>
</head>
<body>
<h1>Number guessing game</h1>
<p id="guesses"></p>
<p id="lastResult"></p>
<p id="lowOrHi"></p>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit">Enter Guess</button>
</div>
<p></p>
</body>
</html>

Your program is all wrong and is actually doing nothing
the only thing that actually executes is everything outside your functions,
and those are being called only when the page is loaded for first time
in order to execute your CheckGuess you need to actually call it :
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
but everything else that is actually outside of your functions are only executed when the page is loading
also you have a while--else statement, that's not even possible
then again... it is outside a function so it is useless
You need to put everything on one single statement
YOU DO NOT NEED A WHILE
once you write something down on the page it will stay there until it reloads
if you write a while like that you will just loop your code endless.
this code and logic is so wrong in so many ways i will sent you a functional code :
<script type="text/javascript">
var guesscount =0;
var randomNumber = Math.floor(Math.random() * 100) + 1;
function checkGuess()
{
guesscount = guesscount +1;
var userGuess = document.getElementById("guessField").value;
document.getElementById('guesses').innerHTML += Number(userGuess)+ '<br>';
CheckResults();
}
function CheckResults()
{
//add here your logics if the number is wrong
if ( guesscount>= 10)
{
document.getElementById("guessField").disabled = true;
document.getElementById("guessSubmit").setAttribute('disabled', 'disabled');
document.getElementById('guesses').innerHTML += 'game Over !';
}
}
</script>
</head>
<body>
<h1>Number guessing game</h1>
<label id="guesses"></label>
<label id="lastResult"></label>
<label id="lowOrHi"></label>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
</div>
<p></p>
</body>
</html>

Related

Why do I have to keep refreshing the page for the output of the code to change and actually follow what I intended it to do?

Apparently I posted a question couple of minutes ago saying that my code was not working because the output was always the same and didnt change even when I put different inputs, but I deleted it because I found out that the problem was that I had to refresh the whole page and answer again to get the intended output. I have to keep doing this everytime I wanted that or else the output would stay the same. Could someone help me figure out why that happens and how to fix it?
The Code:
var q1Agree = document.getElementById("q1-agree");
var q1Neutral = document.getElementById("q1-nuetral");
var q1Disagree = document.getElementById("q1-disagree");
var q2Agree = document.getElementById("q2-agree");
var q2Neutral = document.getElementById("q2-nuetral");
var q2Disagree = document.getElementById("q2-disagree");
var result = document.getElementById("result");
var pnum = 0;
function personalitycondition() {
if (q1Agree.checked) {
pnum += 2;
} else if (q1Neutral.checked) {
pnum += 1;
} else if (q1Disagree.checked) {
pnum += 0;
}
if (q2Agree.checked) {
pnum += 2;
} else if (q2Neutral.checked) {
pnum += 1;
} else if (q2Disagree.checked) {
pnum += 0;
}
if (pnum > 4) {
result.innerHTML = "You are a confident and energetic person.";
} else if (pnum >= 2) {
result.innerHTML = "You are a balanced and level-headed person.";
} else {
result.innerHTML = "You are a reserved and thoughtful person.";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form id="q1">
<h3>You are open about your feelings</h3>
<label for="agree">Agree</label>
<input type="radio" id="q1-agree" name="q1-personality" value="Agree"><br><br>
<label for="nuetral">Nuetral</label>
<input type="radio" id="q1-nuetral" name="q1-personality" value="Nuetral"><br><br>
<label for="disagree">Disagree</label>
<input type="radio" id="q1-disagree" name="q1-personality" value="Disagree"><br><br>
</form>
<form id="q2">
<h3>It is difficult to get you excited</h3>
<label for="agree">Agree</label>
<input type="radio" id="q2-agree" name="q2-personality" value="Agree"><br><br>
<label for="nuetral">Nuetral</label>
<input type="radio" id="q2-nuetral" name="q2-personality" value="Nuetral"><br><br>
<label for="disagree">Disagree</label>
<input type="radio" id="q2-disagree" name="q2-personality" value="Disagree"><br><br>
</form>
<button type="button" onclick="personalitycondition()">Find Your Personality</button>
<p id="result"></p>
</body>
</html>
Plus, I didnt really try anything because I dont know if the problem is related to the code or something outside
In short, the issue is in the JavaScript you've provided. You have defined the pnum variable globally. This means that after the function personalitycondition completes, the pnum function keeps its value, and the starting value of pnum the next time the function executes is not 0 anymore, but instead is what the function left behind itself.
A simple solution would be to put the pnum variable inside the function, so that the variable is reset every time we execute the personalitycondition function. Another solution would be to set pnum to 0 in the start of the function.

Why can't javascript set the value of a HTML form element?

Title says it all, i am setting a value in a variable in a javascript.
I want to set that value as value of the one of the row in my form.
here is the code, this is based on previous similar questions and their accepted answers, but somehow it does not work for me.
<html>
<head>
<script>
var counter = 0;
var limit = 50;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Element " + (counter + 1) + " <input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
</head>
<body>
<form method="POST" align="center">
<script>
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
</script>
<div id="dynamicInput">
Title<br><input type="text" value="" name="myInputs[]" id="someid" disabled>
</div>
<input type="button" value="Add another event" onClick="addInput('dynamicInput');">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I also tried something like:
document.forms[0].myInputs[0].value="Whatever"
inside the script tags, but that also does not work.
Edit_1
I expect some value in the disabled input field, just below the title, but its empty.
Here is the image:
How can I have some value based on a random number generator there?
check the jsfiddle, this is due to how u arrange ur script, you either move ur code below the html, or use onload() event
example
onload="test()"
then you will no need to worry where the js should put
<script>
function test(){
var emotion = "";
var raw = Math.random();
var final = Math.ceil(raw * 4);
if (final == 1)
document.getElementById("someid").value = "A";
else if (final == 2)
document.getElementById("someid").value = "B";
else if (final == 3)
document.getElementById("someid").value = "C";
else if (final == 4)
document.getElementById("someid").value = "D";
}
</script>
https://jsfiddle.net/gw04jhoj/
you can refer to this for more info
Javascript that executes after page load
Your script is running before those HTML elements have been created, and so setting their value will fail, as document.getElementById("someid") doesn't exist yet. You should see this fail in the error console in the browser (F12).
Try moving the script until after you've created the HTML elements in question, or better yet change your script to only execute once the document has loaded.
You should use :
document.getElementById("someid").value="whatever";

inner.html / handlers

as an incoming javascript coder, i'm stuck at a sample exercise...
<script language="JavaScript">
var num1;
var messages;
var answer = document.getElementById("guess").value;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("guess").value;
do {
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
</body>
this is supposed to print:
number of guesses is 5 or fewer: "either you know the secret or you got lucky"
Or number of guesses is 5 or more:"you should be able to do better"
Or number of guesses in 5 tries : "ahah!"
however it's not printing .../././
Initially there are few syntax errors to correct
do {} without while is not valid javascript.
start() is never called. I'm guessing you intended to use window.onload = start or <body onload="start();">
Your script is executed before the HTML elements it is modifying. If you want to access elements from the DOM you should access them within a function and/or place the script at the bottom of the body tag.
<script language="JavaScript"> is deprecated. I think you mean <script type="text/javascript"> although as that is the default the type is optional.
The messages variable is never assigned
You set text as the value to a number input. I suspect you intended to use placeholder="guess a number 1- 32". Note that placeholder is actually used to provide a hint about expected input. Direct instructions should use a label. This doesn't affect your javascript but is worth considering all the same.
Additionally myGuess() currently checks if the submitted value is less than the answer or more. You need to increment a count value and compare against that.
The below example do what you need
<form action="#">
<label for="inputfield">guess a number 1-32</label>
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number">
</form>
<p id="messages"></p>
<script type="text/javascript">
var num1;
var target = 5;
var messages = document.getElementById("messages");
var counter = 0;
var answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value;
if(num1 == answer) {
if (counter === target) {
messages.innerHTML = "Ahah!"
}
if (counter < target) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (counter > target) {
messages.innerHTML = "you should be able to do better";
}
} else {
counter++;
messages.innerHTML = "Keep trying";
}
}
window.onload = start;
</script>
<script language="JavaScript">
var num1;
var messages; // should be initialized inside start because at this moment it doen't exist
var answer;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
window.addEventListener("load", start); // on loading the page call start;
function start() {
messages = document.getElementById("message"); // this should be something
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value; // the id is "inputfield" not "guess"
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
// else if to stop checking again (if is correct but not the best)
else if (num1 < answer) {
messages.textContent = "Either you know the secer or you got lucky!"; //textContent is better than innerHTML
}
// same here
else if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
<div id="message"></div>
</body>
Note: you was using do-while incorrectly (you was messing the while part). Anyway, do-while or any other loop will just loop forever if the answer is not correct because you are not letting the user to re-enter a number. What you need is to check whether the number is correct or not whenevr the user click the button (that parts you had it correct because you used the event listener).
What your code was doing (or supposed to be doing) is check if a user clicks the button and then loop if his answer was incorrect untill the answer is is correct (which is not going to happen because you never give the user another chance to enter a number again. He will get a chance after the function execution is finished. And because of the loop it will never be finished). It was never going to work because the loop waits for the user to enter another number (a correct one) to exit and the user is waiting for the loop to end to enter another number (see the paradox).
What it should do is to wait for the user to enter a number, check that number, prints the message accordingly for that number and then give the user to enter another number. (It is a loop (cycle) already so why need another loop)
The code you need is this:
<body>
<form id="form">
<input id="guessButton" type="submit" value="guess">
<input id="inputfield" type="number" placeholder="guess a number 1-32">
</form>
<div id="messages"></div>
<span id="counter"></span> tries
</body>
<script language="JavaScript">
document.getElementById('form').onsubmit = function() {
return Myguess();
};
var num1;
var messages = document.getElementById("messages");
var counterDiv = document.getElementById("counter");
counterDiv.innerHTML = 0;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function Myguess() {
num1 = document.getElementById("inputfield").value;
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
counter++;
counterDiv.innerHTML = counter;
return false;
}
</script>
You can test it in this JSFiddle.
The function Myguess() is called when the form is submitted. There was no div messages missing in your code, so I added it. I also added the counter span which shows how many tries the player has had. Also the message "guess a number 1-32" is better added as placeholder. I hope that was helpful !

Keep form data with back button

there are many questions similar to this but none of them seem to help with my situation.
I am developing a three step process using Javascript and html
I have 2 forms in the first two steps.each with a next/prev button
I need to be able to go back from step two back to step 1 and still have step ones form data in the fields. I am rather new to javascript any help would be appreciated. I am unsure how to save the form data and then insert it when the user goes back from step 2
EDIT:
I have decided to use JS to hide/show forms, please can someone tell me why my variable never gets to currentStep == 3; this causes issues when going back as it goes back to step one becasue the currentStep value is stuck at 2
var currentStep = 1;
function nextStep() {
if (currentStep ===1){
$("#petmain1").hide();
$("#petmain2").show();
$("#addproduct").show();
$("#firstimage").hide();
$("#secondimage").show();
currentStep = 2;
console.log("Current step is " + currentStep);
}else if(currentStep ===2){
$("#petmain2").hide();
$("#addproduct").hide();
$("#secondimage").hide();
$("#petmain3").show();
$("#thirdimage").show();
$("#firstimage").hide();
currentStep === 3;
console.log("Current step is " + currentStep);
}
}
function prevStep() {
if (currentStep ===2){
$("#petmain1").show();
$("#petmain2").hide();
$("#addproduct").hide();
$("#firstimage").show();
$("#secondimage").hide();
currentStep = 1;
console.log("Current step is " + currentStep);
}else if(currentStep === 3){
$("#petmain3").hide();
$("#thirdimage").hide();
$("#secondimage").show();
$("#petmain2").show();
$("#addproduct").show();
currentStep === 2;
console.log("Current step is " + currentStep);
}
}
You can use localStorage
On navigating from first step to second step you can store the value
if(typeof(Storage) !== "undefined") {
localStorage.setItem("someKey", $("#somField").val());
} else {
//
}
Again on navigating from second to first step check the local storage for the value and assign it to the fields in first form
$("#somField").val(localStorage.getItem("someKey"))
You may use sessionStorage.
HTML
<form>
Username : <input type='text' id='name'> <br />
Password : <input type='password' id='password'> <br />
<input type='button' onclick='storedata()' value='submit'>
</form>
<p id='res'></p>
JS
window.onload = function() {
if (sessionStorage.name && sessionStorage.password) {
document.getElementById("name").value = sessionStorage.name;
document.getElementById("password").value = sessionStorage.password;
}
};
function storedata() {
if(typeof(Storage) !== "undefined") {
var name = document.getElementById("name").value;
var password = document.getElementById("password").value;
sessionStorage.name = name;
sessionStorage.password = password;
document.getElementById("res").innerHTML = "Your datas restored";
} else {
document.getElementById("res").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Working Demo : https://jsfiddle.net/d83ohf6L/

Javascript function stops being recognized

I'm having a problem with the following code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
gallows = new Array("--------\n| |\n|\n|\n|\n|\n=====",
"--------\n| O\n|\n|\n|\n|\n=====",
"--------\n| O\n| |\n|\n|\n|\n=====",
"--------\n| O\n| \\|\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| /\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| / \\\n|\n=====");
guessChoices = new Array("JavaScript", "Navigator", "LiveConnect", "LiveWire");
guessed = [];
function startAgain()
{
guesses = 0;
max = gallows.length - 1;
//guessed = " ";
len = guessChoices.length - 1;
toGuess = guessChoices[Math.round(len*Math.random())].toUpperCase();
displayHangman();
displayToGuess();
displayGuessed();
}
function stayAway()
{
document.game.elements[3].focus();
alert("Don't mess with this form element!");
}
function displayHangman()
{
document.game.status.value=gallows[guesses];
}
function displayToGuess()
{
pattern = "";
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) != -1)
pattern += (toGuess.charAt(i)+" ");
else pattern += "_ ";
}
document.game.toGuess.value=pattern;
}
function displayGuessed(s)
{
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
//document.game.guessed.value=guessed;
}
function badGuess(s)
{
if(toGuess.indexOf(s) == -1) return true;
return false;
}
function winner()
{
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) == -1) return false;
}
return true;
}
function guess(s)
{
if(guessed.indexOf(s) == -1) guessed.push(s);
if(badGuess(s)) ++guesses;
displayHangman();
displayToGuess();
displayGuessed(guessed);
if(guesses >= max)
{
alert("You're dead. The word you missed was "+toGuess+".");
startAgain();
}
if(winner())
{
alert("You won!");
startAgain();
}
}
// -->
</script>
</head>
<body>
<h1>Hangman</h1>
<form name="game">
<pre>
<textarea name="status" rows="7" cols="16" onfocus="stayAway();"></textarea>
</pre>
<p>
<input type="text" name="toGuess" onfocus="stayAway();"> Word to guess<br>
<input type="text" name="guessed" onfocus="stayAway();"> Letters guessed so far<br>
</p>
<p>Enter your next guess.</p>
<p>
<input type="text" name="input" size=1 value="">
<input type = "button" value = "guess" onclick = "guess(game.input.value); game.input.value = '';">
</p>
<input type="button" name="restart" value="---- Start Again ----" onclick="startAgain();">
<script type="text/javascript">
<!--
startAgain();
// -->
</script>
</form>
</body>
</html>
After I click the game.guess button, the first time around, I get the expected output... game.input clears and guessed is displayed. However, the second time I click the guess button with a different value, I receive the error:
guess is not a function
| onclick()
| event = click clientX=77, clientY=33
guess(game.input.value) onclick(line 2)
And I honestly can't figure out why. What am I doing wrong?
(I got the bulk of this code from Mastering JavaScript, Premium Edition, by James Jaworski)
The problem is on these lines:
guess=s[i];
result += guess;
This way you are changing the context of guess. If you change this line to
result += s[i];
Your error will go away.
You are conflicting your function with using same name for a variable.
Remember to define your variables using var keyword and avoid such confusion.
1 - use anonymous functions where possible
2 - declare and use local variables
To avoid conflicts.
In your function displayGuessed(), you are setting the variable guess (which is a function) to the the guessed letters.
You can fix this by defining your function's guess variable (making it distinct from the function) using the "var" keyword:
function displayGuessed(s)
{
var guess;
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
}
Tip: I found this bug easily by using the Firebug plugin for firefox, which lets you step through javascript code line by line, to see where things are going wrong.

Categories