User guesses a number from 1-1000 using functions - javascript

I am trying to make a program that prompts the user to guess a number from 1 to 1000. The program generates a random number and then the user has to guess the number until they get it right. The program alerts the user if their guess is too low or too high. Upon entering the right number, they are congratulated and asked if they want to run it again. I have read my book and even looked online for guidance, but against my best effort all it does is display the text field with the calculate button...no window messages or anything. Please help as I am stumped. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>

There is a } missing in line 45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
}
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>

Jquery way if you mind
var a = Math.floor((Math.random() * 100) + 1);
$(document).ready(function(){
$('#numberrandom').text(a);
});
$('#calculate').bind('click',function(){
entrynumber=$('#entry').val();
if(entrynumber > a){
alert('Your number is higher than it')
}
else if(entrynumber < a){
alert('Your number is lower than it')
}
else if(entrynumber == a){
alert('nice you won')
location.reload();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
<span>generated number: </span><span id='numberrandom'></span>
</div>
</form>
</body>

Related

I'm a beginner and I don't understand how my code works (javascript)

I want user to guess how many fingers are there (Math.random()), but it does not work the way I expect it to and I can't find the mistake.
This is all in a <body> tag:
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>
<script>
var fingers = parseInt(Math.random()*6);
var userInput = document.getElementById("userInput").value;
var i = 0;
var num = document.getElementById("numberOfTries");
function check(){
if (userInput == fingers)
{
alert("You got it!");
}
else{
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
</script>
So, the way I see this: when the page loads it creates a random number (fingers), and then I just compare that number to the number in input.
Why doesn't it work?
You had just a small error. You only checked their input once. See I moved to the function scope and now it works.
var fingers = parseInt(Math.random() * 6);
console.log(fingers);
var i = 0;
var num = document.getElementById("numberOfTries");
function check() {
// This was in the wrong place. We need to check user input each time.
var userInput = document.getElementById("userInput").value;
if (userInput == fingers) {
alert("You got it!");
} else {
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>

Adding JavaScript calculation function to HTML form

I am trying to link a basic calculation in an external JavaScript
The form is pretty simple and the function just checks to make sure the step number is even. I have reviewed the code many times, but when I enter the numbers and hit submit nothing happens. Any suggestions? Its seems like I just don't have the function and input elements linked correctly.
here is the code:
function evenNumbers() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="number" id="startNumber"/><br/>
<label>End: </label>
<input type="number" id="endNumber"/><br/>
<label>Step by:</label>
<input type="number" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
Try this:
In .js file
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
I have removed your actual code for now, because it has some issues whereby you can end up in an infinite loop (I definitely did and it crashed Chrome 😊).
Your issue was in your HTML
Before
<button onclick("evenNumbers();")>Submit</button>
After
<button onclick="evenNumbers();">Submit</button>
function evenNumbers() {
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
alert(startNumber + ',' + endNumber + ',' + stepNumber);
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
function evenNumbers() {
//var evenNumberBtn = document.querySelector("button");
//evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers()">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
The first two lines inside evenNumber function need to be outside the function, Otherwise your code never reaches inside that block.
$( document ).ready(function() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
function evenNumbers() {
/*
your code here
*/
}
});
Also the logic inside the evenNumbers seems wrong. You might need to change that too.

Why is `pieceOfText` undefined?

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?
You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

Part of my coding in javascript not working

For some reason, the validation for duration is having problem such as when I try to type 30000000 for the duration and submit,it just never do its validation but the rest of the validation works for some reason.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var y =document.forms.myForm.percentage.value;
if(y>=0 && y<=100)
{
return true;
}
else
{
alert("Percentage output must be between 0 and 100");
return false;
}
var k =document.forms.myForm.duration.value;
if(k>=0 && k<=30000)
{
return true;
}
else{
alert("Error");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return validateForm();">
Enter access token: <input type="text" name="token">
Enter device id: <input type="text" name="id">
Enter output percentage: <input type="text" name="percentage">
Enter duration(in milliseconds) of output: <input type="text" name="duration">
<input type="submit" value="Submit">
</form>
</body>
</html>
Cause:
function validateForm() {
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var y =document.forms.myForm.percentage.value;
if(y>=0 && y<=100)
{
return true; //<---- You leave your code here!!
}
else
{
alert("Percentage output must be between 0 and 100");
return false;
}
var k =document.forms.myForm.duration.value;
if(k>=0 && k<=30000)
{
return true;
}
else{
alert("Error");
return false;
}
}
Look at the arrow in the code I entered.
In the percentage check, you always return! The duration check is never reached. You should remove all your if/else cases which ends in return true, only check on error and return false in that case. Otherwise return true as the last line of your method.
If you want to alert on more than one error, you can do something like the following, though you'd have to format the alert message text so that each error is on its own line:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var errors = [];
var x = document.forms["myForm"]["token","id","percentage","duration"].value;
if (x == "") {
alert("There are empty fields");
return false;
}
var percentage = document.forms.myForm.percentage.value;
if(!(percentage >= 0 && percentage <= 100)) {
errors.push("Percentage output must be between 0 and 100");
}
var duration = document.forms.myForm.duration.value;
if(!(duration >= 0 && duration <= 30000)) {
errors.push("Duration output must be between 0 and 30,000");
}
if (errors.length > 0) {
alert(errors);
}
}
</script>
</head>
<body>
<form name="myForm" onSubmit="return validateForm();">
<p>Enter access token: <input type="text" name="token"/></p>
<p>Enter device id: <input type="text" name="id"/></p>
<p>Enter output percentage: <input type="text" name="percentage"/></p>
<p>Enter duration(in milliseconds) of output: <input type="text" name="duration"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>

Categories

Resources