Use the prompt() method to ask the user what the maximum number should be. The prompt should be in a loop with validation as demonstrated previously in the course making sure that the inputted value is a positive number. If the user inputs a decimal, simply round it.
When a valid number is inputted, change the content of the instructions to specify guesses between 1 and N.
When the user presses the guess button, validate the input:
If the guess is not a number, display a message: "That is not a number!"
If the guess is out of range (1 to N), display a message: "That number is not in range, try again."
Using an array, keep track of each guess by the user. When the user wins the game by guessing correctly, add the number of guesses and the list of guesses to the victory message. For example:
"You got it! It took you 5 tries and your guesses were 3, 14, 7, 9, 5"
Do not count invalid guesses (not numbers or out of range).
Since you are tracking the guesses, add validation to check if a number has already been guessed. If it has, display a message and do not count it as a guess.
HTML File:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>Higher - Lower</title>
</head>
<body>
<div class="container">
<h1>Higher Lower</h1>
<p>Guess a number between 1 and <span class="max-number">N</span></p>
<div class="row">
<div class="col-lg-3 cold-md-6">
<form>
<div class="form-group">
<label>Your guess:</label>
<input type="text" id="userInput" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick= "do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p>
</div>
<script src="HigherLowerEnhanced.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudfare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
JavaScript File:
let maxNumber;
// use an infinite loop that continues until a users input is validated
while (true) {
maxNumber = prompt("What should the maximum number be?");
// check if the user input is actually a number
if (isNaN(maxNumber)) {
// keeps the loop going until input is validated
continue;
}
// check if the number is a decimal
if (!Number.isInteger(maxNumber)) {
// function that rounds numbers
maxNumber = Math.round(maxNumber);
}
if (maxNumber < 1) {
console.log("Please Enter number more than 0");
continue;
}
// function to set the spans value to the input number
const maxNumberSpan = document.querySelector('.max-number');
maxNumberSpan.innerHTML = maxNumber;
break;
}
// generate random number between 1 and infinite
let num = Math.floor(Math.random() * maxNumber) + 1;
// function stores users guesses
const inputArray = [];
document.querySelector('.btn').addEventListener("click", (e) => {
// prevents page from refreshing after you click submit
e.preventDefault();
// call do_guess() function on click
do_guess();
});
// do_guess function
function do_guess() {
// get message div
let message = document.getElementById("message");
// get input value
let guess = Number(document.getElementById("guess").value);
// if input is not a number
if (isNaN(guess)) {
message.innerHTML = "This is not a number";
// return function (so that user can submit another number)
return;
}
// if number is out of range
if (guess < 1 || guess > maxNumber) {
// show this message
message.innerHTML = "That number is not in range, try again";
// return function
return;
}
// indexOf() function finds guess in inputArray
if (inputArray.indexOf(guess) != -1) {
// when the guessed number is not found in the array it will return -1
message.innerHTML = "You already have tried this number";
return;
}
// now we have checked validation of input push guessed number on array
inputArray.push(guess);
// if input is equal to num
if (guess == num) {
message.innerHTML = "You got it! It took you " + inputArray.length + " tries and your guesses were " + inputArray.toString();
}
// if guess is more
else if (guess > num) {
message.innerHTML = "No, try a lower number.";
}
// if guessed number is less
else {
message.innerHTML = "No, try a higher number.";
}
}
Error:
[Running] node "/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js"
/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js:6
maxNumber = prompt("What should the maximum number be?");
^
ReferenceError: prompt is not defined
at Object.<anonymous> (/Users/tonyjones/Desktop/HigherLowerEnhanced/HigherLowerEnhanced.js:6:9)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.1
[Done] exited with code=1 in 0.324 seconds
You are trying to use prompt. Node.js does not provide a native prompt function. Web browsers do.
Ditto the document object.
You have an HTML document. Node.js does not centre on HTML documents. Web browsers do.
Run your code in a web browser instead of in Node.js.
Related
I have the randomizer working, My issue is getting the user's input. I can't seem to figure out how to trigger the input. I used "window.alert" as well as "console.log" but nothing happens. I'm very new to this.
This is my HTML:
<DOCTYPE html>
<html>
<body>
<h2> Guessing For Random Numbers! </h2>
<p> A random number between one (1) and ten (10) will be selected. Try to guess the
result! Input your answer: </p>
<script src= "RandomNumberMaker.js">
</script>
</body>
</html>
This is my JavaScript:
var number = window.alert("Please Enter A Number Between One and Ten: ");
var random = Math.floor(Math.random() * 10) + 1;
if (random == number)
{
document.write ("Your Guess Was Correct!");
document.write(random);
}else
{
document.write ("Your Guess Was Incorrect. The Correct Answer Was: " + random);
}
You can use prompt to get a user input as sort of alert type
var number = window.prompt("Please Enter A Number Between One and Ten: ");
var random = Math.floor(Math.random() * 10) + 1;
if (random == number) {
document.write("Your Guess Was Correct! It is" + number);
document.write(random);
} else {
document.write("Your Guess Was Incorrect. The Correct Answer Was: " + random + " not " + number);
}
<h2> Guessing For Random Numbers! </h2>
<p> A random number between one (1) and ten (10) will be selected. Try to guess the result! Input your answer: </p>
I'm completing some exercises from a javascript course (they are only meant for practice, I don't have to send my solutions) and when I'm trying to do a custom validation using regular expressions, capturing the submit event. The problem is that, if I enter an invalid input the first time, sometimes even if I correct it the custom validity message keeps showing up, and the console.log that show how many times the user tried to submit the form doesn't work, as if the submit event didn't even happen (for example: 1st input: "a", 2nd input: "aa", the custom validity message shows up and nothing can be loaded to the console, as if the submit event didn't even happen,but if I enter a valid input the first time, the error dissapears). I don't know if the way to solve this problem is to add an event listener for the blur event of the input and remove the custom validity there if necessary. A part of the code looks something like this (I added changes, the original one was simpler and had even more problems):
<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>Example of form validation</title>
</head>
<body>
<form>
<fieldset>
<legend>Enter your user data</legend>
<div class="group">
<label for="name">Name</label>
<input id="name" type="text" placeholder="Example: John Doe">
</div>
</fieldset>
<button>Continue</button>
</form>
<script>
let form = document.querySelector("form")
let i = 0
form.addEventListener("submit", function(e){
i++
console.log(`You tried to submit this form ${i} times`)
e.preventDefault()
let input_name = document.querySelector("#name")
let value = input_name.value
let words = [value.split(" ")[0], value.split(" ")[1]]
let words_joined = words[1] ? words[0] + " " + words[1] : words[0] // this ugly conditional statement prevents the program from joining a string with an undefined value
let regex = /^\w{2,}(\s+\w{2,})*$/
let matches = words_joined.match(regex)?.length
try {
if(matches){
handleSuccess.call(input_name)
} else {
let err_msg = `You must enter 1 or 2 words with at least 2 characters each`
input_name.setCustomValidity(err_msg)
throw new Error(err_msg)
}
} catch (err){
handleError.call(form, err) /// I prefer to send to both handlers the apropiate "this"
}
})
function handleError(err){
console.log(err)
}
function handleSuccess(){
this.setCustomValidity(``)
this.classList.add(`success`)
console.log(`The input with the id "${this.id}" is valid`)
this.parentElement.parentElement.parentElement.submit() // submits the form
}
</script>
</body>
</html>```
If I remove the setCustomValidity() function everywhere, the problem dissapears, but that isn't very practical. At least it seems like that is the root of the problem.
Problem solved thanks to the help of Ivar. I made some changes to the original code (those are reflected on the original post, sorry for not posting them anywhere else), and added the following lines:
let value = input_name.value
let words = [value.split(" ")[0], value.split(" ")[1]]
let words_joined = words[1] ? words[0] + " " + words[1] : words[0] // this ugly conditional statement prevents the program from joining a string with an undefined value
// words_joined only contains the first 1 or 2 words
let regex = /^\w{2,}(\s+\w{2,})*$/
let matches = words_joined.match(regex)?.length
try {
if(matches){
value = words_joined // if there were more than 2 words, only the first 2 remain in the value of the input with the id "name"
handleSuccess.call(input_name, "don't submit")
} else {
let err_msg = `You must enter 1 or 2 words with at least 2 characters each`
input_name.setCustomValidity(err_msg)
throw new Error(err_msg)
}
} catch (err){
handleError.call(form, err) /// I prefer to send to both handlers the apropiate "this"
}
})
function handleError(err){
console.log(err)
}
function handleSuccess(shouldSubmit){
this.setCustomValidity(``)
this.classList.add(`success`)
console.log(`The input with the id "${this.id}" is valid`)
if(shouldSubmit != "don't submit") this.parentElement.parentElement.parentElement.submit() // submits the form
}```
the last two functions are almost equal to the ones written in the original question, but with the addition of the "shouldSubmit" parameter and a conditional statement for the last one. Basically, the unpredictability of the error seems to have been caused by how regular expressions with the "g" flag work in js, and it was solved by assigning the return value of the match() function to a variable and using that variable on the rest of the scope. And the main problem, that error showing up even after correcting an invalid input, was ocurring because the custom validity was showing up between submits. Now that an event listener for the "change" event of the input is added, this is corrected. Thanks for the help!
I have been given this logic table that I need to use if else statement to get a promotion price based on user input.
How to declare that logic table in javascript? So that I can print out the correct output based on the table.
For example; if user input is 5, so, I need an expected output of (price 3 + price 2).
function checkQuantity() {
let userInput = document.getElementById('quantity').value;
userInput = Number(userInput); //Convert string to number data type
var pizzaPrice = 6.45;
var pizzaPrice2 = 12.00;
var pizzaPrice3 = 14.00;
if (!userInput) {
console.log("Please enter a valid pizza quantity");
} else if (isNaN(userInput)) {
console.log("Error!!");
} else if (userInput < 1) {
console.log("Minimum pizza order is 1.");
} else {
document.getElementById('message').innerHTML = 'Number of pizza : ' + //Price hasn't been declared yet;
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
<script src="linked.js"></script>
</head>
<body>
<h1>PizzasOnly ordering form</h1>
<p>Simply enter the number of pizzas you want into the input below to find out the cost of your order</p>
<form action="#" method="post" id="orderForm" onsubmit="return checkQuantity()">
<p>
<label for="quantity">Enter number of pizzas wanted:</label>
<input name="quantity" id="quantity" value="">
</p>
<p>
<input value="Total cost" type="submit">
</p>
</form>
<div id="message"></div>
</body>
</html>
The formula can be assembled as a one-liner:
~~(i/3)*price + xtra[i%3]
~~ (the repeated application of the "bitwise NOT operator") is a shorthand notation for Math(floor(), % is the modulo operator that will return the remainder of a division, the rest should be clear.
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i)) )
In this later version I defined the function price(). It can be called with one argument (i: number of pizzas) as you can see above.
The optional arguments p3 (price for a bundle of 3) and xtr (addon for zero, one or two extra pizzas) can be supplied if you want to use a different pricing structure than the default one, see here:
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i,16,[0,6,11])) )
So I'm trying to prompt the user to enter as many numbers as they want until they hit -999 to quit. I need to check how many even numbers they entered, how many odd, the sum of the odd, the even, and their average for even and odd. I'm only a little ways into the code but I already can't get the simple loop to execute or the prompt to "prompt". The prompt is prompted by a clicking on a button and the function is attached to it.
function meditation() {
var i = parseInt(prompt("Enter an integer or (Enter -999 to quit)"), 10);
do {
if (i % 2) {
document.getElementById("odd").innerHTML = i + " is odd.";
} else if {
document.getElementById("even").innerHTML = i + " is even.";
}
} while (i != -999)
}
<header>
<h1>Odd and Even Log</br>
</h1>
</header>
<h2> Click on the button to enter the meditation numbers.</h2>
<h3>I will keep track of odd and even meditation numbers.</h3>
<button onclick="meditation()">Enter the meditation numbers.</button>
<br>
<p>The meditation numbers: </p>
</section>
I'm writing a program that will calculate a number entered by the user multiplied by 2.
I realised I need a for loop so that the Value will increment by 1 and multiple by 2
The problem is I want to know how to run this loop only 10 times
- at the current moment it will run for ever and I had to place an if statement to break out of the loop if the value reaches 50.
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (value;; value++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
if (value > 50) {
break;
}
}
you can use a counter variable to keep a check on number of iterations. I am guessing you want to increase value by 1 after each iteration. You can do something like this:
//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (var i=1;i<=10; i++) {
value2 = value * 2;
document.write(`${value} multiply 2 -> ${value2}`);
document.write('<br>');
//i placed this if statement to break out of the for loop as it //will run forever
value++;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--
<script type="text/javascript" src="js.js"></script>
-->
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Multiple By 2</h2>
<input type="text" id="num"/>
<button onclick="multiply()">multiply by 2</button>
<script>
function multiply() {
var number = document.getElementById("num").value;
for(i=1;i<11;i++){
console.log(number*i);
}
}
</script>
</body>
</html>