Why is my do..while loop not working? (prompt not executing) - javascript

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>

Related

What can I do to resolve this error code isssue?

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.

A JavaScript Program where a number is generated and the user tries to guess it. My Issue is input

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>

Accessing and manipulating HTML input using JavaScript

I'm an new amateur programmer that is having trouble using HTML and JavaScript together. We were tasked to make a simple program that asks us what's the maximum number, I made the logic but still having trouble with this case.
Currently this is the progress with my code
var num1;
var num2;
var num3;
var max;
if (num1 < num2) {
if (num2 < num3) {
num3 = max;
} else if (num2 > num3) {
num2 = max;
}
} else if (num1 > num2) {
if (num1 > num3) {
num1 = max;
} else if (num1 < num2) {
num2 = max;
}
}
alert("The maximum number is: " + max);
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>
The main problem with your code is that it runs straight away, long before a user has entered any number. The next problem with it is that you never read the values from the inputs.
What you instead want is for the code to wait until an event occurs - which, in your case is the event, that the user clicks the Enter button.
For reacting to user actions (and more), Javascript has the concept of eventListeners, which you can add to any element. There is many different types of events; the one you care about here is the click event.
To add it to the button, you first need your Javascript to learn where your button element is. To find it in the page, Javascript offers the document.querySelector() method.
Once you have found it, you can call the addEventListener() method on the element (all HTML elements have this method built-in).
For an explanation of the rest, check the source code comments (lines that begin with //):
// first we need to find the button in the page,
// so we can access it in our Javascript
// the following finds the first <button> element in the page.
const button = document.querySelector('button');
// every HTML element has a addEventListener method
// that takes two arguments:
// the first is the name of the event you want to listen to (String),
// the second is a function that will be executed every time
// the event occurs.
button.addEventListener('click', function() {
// when the user clicks the button, we read what is in the inputs.
// to do that, we first need our JS to find the inputs.
// in this case this is especially easy because each of them has a
// unique identifier (id), so we can use
// document.getElementById(id)
// to find it.
// Once found, we immediately read the value from the input.
let aValue = document.getElementById('a').value;
let bValue = document.getElementById('b').value;
let cValue = document.getElementById('c').value;
// because the value of any input element is always a String,
// we now convert it to a Number.
aValue = parseFloat(aValue);
bValue = parseFloat(bValue);
cValue = parseFloat(cValue);
// now we use another built-in object, Math, and on it, the
// Math.max function, to find the largest number.
const maxValue = Math.max(aValue, bValue, cValue);
// to output the maxValue, we use console.log rather than
// alert. To see the output in the browser, open the browser's
// developer tools (F12 on Windows), and click the "Console" tab.
// To make sure not to output anything if no number was entered
// before the button was clicked, we check if maxValue is a proper
// number. Javascript has the NaN datatype (Not a Number),
// and you can check for it using isNaN(variable)
if (!isNaN(maxValue)) { // if maxValue is not "Not a number"
console.log("The maximum number is: " + maxValue);
}
})
<h1>Laboratory 06</h1>
<p>2. Write a JavaScript program to determine the maximum number using 3 input box.</p>
<blockquote>
<label for=num1>First number:</label><br>
<input type="text" id="a" name=num1><br><br>
<label for=num2>Second number:</label><br>
<input type="text" id="b" name=num2><br><br>
<label for=num3>Third number:</label><br>
<input type="text" id="c" name=num3><br><br>
<button type="button">Enter</button>
</blockquote>

Why is my javascript/html document bypassing my attempt to check if a string is empty?

Edit: |SOLVED| user Jaromanda X's solution worked perfectly. Thank you
My goal is to have the user enter a bit of text into the textbox and submit it. I want to check and see if the textbox is empty and, if so, it should alert the user that a name needs to be entered. If it is not empty I want it to display the text they had entered.
The issue is this: Every time I hit submit it takes the value of the textbox - empty or not - and displays it without ever alerting the user of an empty text field. I feel like I'm missing something very basic. Thank you for your help!
HTML File
<body>
<div id="statusBar">
<h1 id="playerName"></h1>
<h2 id="playerHP"></h2>
</div>
<div id="gameWindow">
Player Name: <input id="inputName" type="text" name="Player Name">
<br>
<input type="button" value="submit" onclick="getStats()";>
</div>
<script src="script.js"></script>
</body>
JS File
function getStats(){
if(document.getElementById("inputName").len === " "){
alert('You must enter a name!');
} else {
var playerHP = 10;
var playerName = document.getElementById('inputName').value;
//Display player name on screen
document.getElementById('playerName').innerHTML = playerName;
//remove the value placed in the text box
document.getElementById('inputName').value = "";
//Display the player's HP
document.getElementById('playerHP').innerHTML = playerHP;
}
};
Change your if statement to:
if (document.getElementById("inputName").value.length === 0) {
Right now you're trying to get a property len of your <input> element, which doesn't exist. You should first be getting the value of the input, and checking if its length is zero. Hence, .value.length.
It should be:
if (document.getElementById("inputName").value === "") {
// do something
}
You're not using the right conditional.
Replace the
document.getElementById("inputName").len
with
document.getElementById("inputName").value.length === 0.

HTML Tic-Tac-Toe Game Winner Announcement

I should start off by saying that I am SUPER new to this (not just stack overflow, but also any sort of coding in general). I'm taking a very basic intro course right now, and one of our assignments is to create a tic-tac-toe game in an HTML box.
I searched for answers to this question specifically, but anything I found was extremely difficult for me to comprehend (note: writing this code is the most complex coding I have done so far in my life, so that's what level I'm at).
I understand the dynamics of creating the space (table) for the game, and embedding the buttons into the different cells to give players choices. However, for extra credit they've offered us the choice of making the code determine who the winner is. Any insight on where to start with this would be much appreciated.
I'm not even certain where to start, but I imagine that I need to write another javascript code to add into the game. Here's what I have so far (I have only included one row in order to minimize the length of this post):
function RowOneBoxThreeYButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_Three");
x.innerHTML = "Y";
x.style.color = "white";
}
function RowOneBoxThreeXButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_Three");
x.innerHTML = "X";
x.style.color = "white";
}
function RowOneBoxTwoYButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_Two");
x.innerHTML = "Y";
x.style.color = "white";
}
function RowOneBoxTwoXButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_Two");
x.innerHTML = "X";
x.style.color = "white";
}
function RowOneBoxOneYButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_One");
x.innerHTML = "Y";
x.style.color = "white";
}
function RowOneBoxOneXButton() {
var x = document.getElementById("Initial_Choice_Row_One_Box_One");
x.innerHTML = "X";
x.style.color = "white";
}
<html>
<body>
<table style="width:100%; background-color:black" border="2">
<tr>
<td>
<p id="Initial_Choice_Row_One_Box_One" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="RowOneBoxOneXButton()">Choose X</button>
<button onclick="RowOneBoxOneYButton()">Choose Y</button>
</td>
<td>
<p id="Initial_Choice_Row_One_Box_Two" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="RowOneBoxTwoXButton()">Choose X</button>
<button onclick="RowOneBoxTwoYButton()">Choose Y</button>
</td>
<td>
<p id="Initial_Choice_Row_One_Box_Three" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="RowOneBoxThreeXButton()">Choose X</button>
<button onclick="RowOneBoxThreeYButton()">Choose Y</button>
</td>
</tr>
</body>
</html>
Thanks so much everyone! And sorry if my formatting is wrong/I didn't search hard enough or properly for this answer. Happy to improve in all aspects (including formatting my posts here!).
One very important concept in programming is not repeating yourself. You have written essentially the same function six times over. OK, there are some minor differences, like using a different element id each time, and showing either an "X" or a "Y". But the flow of each function is essentially the same.
One thing you want to do is collapse all of those repetitions into one function, but use variables to make that one function behave differently depending on what just happened. You can do that by entering parameters into the function call. In this case, each button click sends different a different row number, box number and letter choice string to the same function.
Note that the row and box numbers start with zero rather than one, even though your id's have names that use "One" as the first "number". Get used to starting to count from 0 instead of 1. It happens a lot in coding.
Use those passed in values to select a different x each time, and to show a different letter each time.
To check if there is a winner, you first of all need to have some way of remembering all the values in the game. One way is to use an array. I don't know if you have learned about arrays yet, but here's a quick lesson:
var myArray = ["A", "B", "C", "D"];
alert(myArray[0]); // shows "A"
alert(myArray[2]); // shows "C"
myArray[2] = "blah blah";
alert(myArray[2]); // shows "blah blah";
Each time someone clicks a button, remember their choice in the array. That way they can be checked. Now, also each time someone clicks a button, check to see whether all the array values are the same as the most recently chosen value. If they are, then you have a winner, at least in this one-dimensional version of tic-tac-toe. Of course, it would be slightly more complicated in a full 3x3 game, but most of the same concepts would apply.
Well, best of luck with your programming...
var textNumbers = ["One", "Two", "Three"]; // this array allows you to recreate the id's using array positions
var choices = ["", "", ""]; // this is where the letter choices will be remembered
function makeMove(row, box, letter) { // this function is called every time any button
// with this 'onclick' handler is clicked
// it will be passed the values seen in each
// button element onclick attribute value
// this single row allows you to recreate all the id's using the values passed in to the function
var x = document.getElementById("Initial_Choice_Row_" + textNumbers[row] + "_Box_" + textNumbers[box]);
// this allows you to pass either "X" or "Y" into the element, depending on which button was clicked
x.innerHTML = letter;
x.style.color = "white";
// remember the choice that was just made by putting the latest letter choice
// into the choices array at the position for this box
choices[box] = letter;
// create a place to hold a message
var msg;
// after each click, check if there is now a winner
// i.e. check if all boxes in this row are the same as the latest choice
if (
(choices[0] === letter) && // if the remembered choice for the first box is the latest choice AND
(choices[1] === letter) && // if the remembered choice for the second box is the latest choice AND
(choices[2] === letter) // if the remembered choice for the third box is the latest choice
) { // ...then announce the new winner
msg = "We have a winner! ===> The '" + letter + "' team!";
} else { // otherwise, continue to say that there is no winner
msg = "No winner yet.";
}
// show the message
var y = document.getElementById("winner");
y.innerHTML = msg;
}
<table style="width:100%; background-color:black" border="2">
<tr>
<td>
<p id="Initial_Choice_Row_One_Box_One" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="makeMove(0, 0, 'X')">Choose X</button>
<button onclick="makeMove(0, 0, 'Y')">Choose Y</button>
</td>
<td>
<p id="Initial_Choice_Row_One_Box_Two" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="makeMove(0, 1, 'X')">Choose X</button>
<button onclick="makeMove(0, 1, 'Y')">Choose Y</button>
</td>
<td>
<p id="Initial_Choice_Row_One_Box_Three" style="color:white">Click a Button to Choose "X" or "Y"</p>
<button onclick="makeMove(0, 2, 'X')">Choose X</button>
<button onclick="makeMove(0, 2, 'Y')">Choose Y</button>
</td>
</tr>
</table>
<p id="winner">No winner yet.</p>

Categories