I am trying to loop between two numbers and to return all prime numbers between them. In the first function isNumberPrime, I check if the number is prime and return 0 if it is not and 1 if it is prime. In the second function I am trying to loop between two numbers and to check if the flag is = 1, I push the number in the array. But, I can not see where the problem is?
function isNumberPrime(flag) {
let number;
let divider;
if ((number != 2 || number%2 === 0) || number === 1){
flag = 0; //not prime number 0
}
else {
divider = 3;
while(divider <= number/2){
if (number%divider === 0){
falg = 0;
break;
}
divider = divider + 2;
}
if(divider > number/2){
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
for (let i = lowerNumber; i <= higherNumber; i++) {
isNumberPrime(i);
if (isNumberPrime(i) == 1){
allPrimes.push[i];
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
I have identified and fixed below issues with your code.
Issues
In isNumberPrime function, you expect flag as a function prameter. Thats wrong. The parameter should be the number
There is a typo error flag was misspelled as falg inside isNumberPrime
The condition number != 2 will assume all the numbers other than 2 as not prime. So removed that.
Also the syntax for Array.push is wrong. it should be allPrimes.push(i) and not allPrimes.push[i]
I have made the lower boundary and upper boundary as the max value between input value and 0 to avoid negative numbers.
Also I have used Math.ceil() in the starting number to take number greater than or equal to input and Math.floor() in ending number to take number less than or equal to input in case of decimals.
I have updated looping function call as looping(+lowerNumber, +higherNumber), to make the parameter number. The value fetched from an input will be string by default.
If you want the element to be inside the form, you can wrap the elements inide a form. But a button inside a form will be treated as a submit button. So you have to explicitly make the button type="button" or you have to preventDefault on form submit. I went for the second approach in the updated fiddle.
Working Fiddle
function isNumberPrime(number) {
let flag;
let divider;
// Wrong: number != 2 will assume all the numbers other than 2 as not prime
if (number % 2 === 0 || number === 1) {
flag = 0; //not prime number 0
}
else {
divider = 3;
while (divider <= number / 2) {
if (number % divider === 0) {
flag = 0; // Typo error fix
break;
}
divider = divider + 2;
}
if (divider > number / 2) {
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
const lowerBoundary = Math.ceil(Math.max(lowerNumber, 0));
const higherBoundary = Math.floor(Math.max(higherNumber, 0));
for (let i = lowerBoundary; i <= higherBoundary; i++) {
const isPrime = isNumberPrime(i);
if (isPrime == 1) {
// Wrong syntax of `Array.push` fixed
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = +input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = +input2.value;
let output = document.getElementById("output");
if (higherNumber > lowerNumber) {
output.innerText = 'All primes between ' + lowerNumber + ' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
} else {
output.innerText = 'Lower boundary should be smaller than the higher';
}
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers);
function submitForm(event) {
event.preventDefault();
}
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<form>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</form>
You have some problems as follows:
First push methods are used in wrong way and the right way is
allPrimes.push(i)
Second you are using number while you didn't initialize the variable,
so initialize it let number = flag;
Third you need to check number === 2 instead of number != 2.
lowerNumber and higherNumber is string, so convert it to number by + operation
Here is working sample:
function isNumberPrime(flag) {
let number = flag;
let divider;
if ((number === 2 || number%2 === 0) || number === 1){
flag = 0; //not prime number 0
}
else {
divider = 3;
while(divider <= number/2){
if (number%divider === 0){
falg = 0;
break;
}
divider = divider + 2;
}
if(divider > number/2){
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
debugger
for (let i = +lowerNumber; i <= +higherNumber; i++) {
if (isNumberPrime(i) == 1){
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
isNumberPrime() algorithm was incorrect, also you had it take a flag instead of number argument.
looing() used push[i] used instead of push(i).
enterNumbers() passed two strings to looping() instead of integers; aggressive type checks in logging().
function isNumberPrime(number) {
if(number < 2) return false;
for(let i = 2; i <= number / 2; i++) {
if(!(number % i)) return false;
}
return true;
}
function looping(lowerNumber, higherNumber) {
if(lowerNumber == "" || !Number.isInteger(lowerNumber) || lowerNumber < 0 || higherNumber == "" || !Number.isInteger(higherNumber) || higherNumber < 0) {
console.error("looping is called with invalid arguments");
return [];
}
let allPrimes = [];
for(let i = lowerNumber; i <= higherNumber; i++) {
if(isNumberPrime(i)) {
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(Number(lowerNumber), Number(higherNumber)) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
You have a few issues here:
In your isNumberPrime function:
You are returning flag while it is also the input param of the function. and you are checking number while it was only declared but never assigned any value.
There is an issue with the condition which is why every number you will input will result in flag being equals to 0. So instead of using and OR operator you should use AND.
You have a typo in the else statement falg instead of flag.
So it should look like this:
function isNumberPrime(number) {
//switched between the flag and number
let flag;
let divider;
if (
(number != 2 && number % 2 === 0) || //changed || to &&
number === 1
) {
flag = 0;
} else {
divider = 3;
while (divider <= number / 2) {
if (number % divider === 0) {
flag = 0; //falg to flag
break;
}
divider = divider + 2;
}
if (divider > number / 2) {
flag = 1;
}
}
return flag;
}
In the looping function:
You used square brackets push[i] when pushing the values into the array. You need to use round brackets push(i)
Related
Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>
I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html
just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.
In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.
More Details:
Program should receive a number and continue receiving numbers [from users input] until
a zero is entered. When a zero is entered, the program should output how many positive and how
many negative numbers have been entered, and then stop.
So far I've only been able to enter one number at a time in the textfield and only been able to output one value that is either positive or negative.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button onclick="check()">Submit</button>
</body>
</html>
Javascript
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var posCount = 0;
var negCount = 0;
if (x > 0) {
posCount++;
}else{
negCount++;
}
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
You could try appending the data to a hidden input element:
function check() {
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var totals = document.querySelector("#totals");
var posCount = totals.dataset.positives;
var negCount = totals.dataset.negatives;
if (x === 0) {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
totals.dataset.positives = 0;
totals.dataset.negatives= 0;
} else if (x > 0) {
totals.dataset.positives = ++posCount;
} else {
totals.dataset.negatives= ++negCount;
}
}
<p>Enter number (Press 0 to stop)</p>
<input type="text" id="num">
<input type="hidden" id="totals" data-positives='0' data-negatives='0'>
<button onclick="check()">Submit</button>
UPDATE
To achieve this, you can create a positive and negative variable outside of the count function and then check each input value; if the value entered zero, you can call your alert function and print the result.
Here is the working code:
var posCount = 0;
var negCount = 0;
function printOutput () {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
var x = parseInt(document.getElementById("num").value);
document.getElementById("num").value = ''
if (x > 0) {
posCount++;
}else if (x < 0){
negCount++;
} else {
printOutput();
// re-initiate value
posCount = 0;
negCount = 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button id="submit-btn" onclick="check()">Submit</button>
</body>
</html>
I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.
My goal is to keep track of the attempts made in the game. This is my code so far.
I have edited this post to understand difference between count = 0 and count = 1.
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.getElementById("attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let count = 1
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value;
if (guessValue < randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too low";
count++
} else if (guessValue > randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too high";
count++
} else {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "You guessed correctly in " + count++ + "
attempts";
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Guess the number</title>
</head>
<body>
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
<script src="script.js"></script>
</body>
I can't understand why attempt.innerHTML won't work. It doesn't show up on the page like "result" does.
You are declaring a global attempt variable outside the function which holds the html element and then you are declaring a local attempt variable in your function which will always be 1.
Declare a counter outside the function and then increment it everytime your function is called.
Also in your answer you are only incrementing the count and updating the attempt.innerHTML inside your if else block under specific conditions. You want to move this code outside of the if else block so it updates on every guess.
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let attempt = document.querySelector(".attempt")
let attemptCounter = 0
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value
// Increment Attempts by 1
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
}
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
This is a simplified function version of setting up multiple number guessing games on a single page. All game related data is kept in dataset attributes num and try of the associated input field.
function guess(id){
let el = document.getElementById(id);
el.dataset.try=0;
el.dataset.num = Math.floor(Math.random() * 30) + 1;
el.onchange=()=>el.nextElementSibling.innerHTML =
"Attempt "+(++el.dataset.try)+":<br>Your guess is "
+["too low.","correct!","too high."]
[Math.sign(el.value-el.dataset.num)+1]
}
guess('guess1');guess('guess2');
<h1>GUESS SOME NUMBERS:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess1">
<div></div>
<p>Enter another guess:</p>
<input type="number" id="guess2">
<div></div>
You're redefining the attempt variable in a local scope as an integer which is overriding the reference to the document element. When you use "innerHTML" your using it on the localized attempt (an integer not the document element)
Try this:
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.querySelector(".attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
button.addEventListener("click", checkGuess)
let attemptCount = 1 // Renamed this from attempt and moved to global scope
function checkGuess() {
let guessValue = document.getElementById("guess").value
attempt.innerHTML = "Attempt n: " + attemptCount
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
attemptCount++;
}