Problem with solving equations in JavaScript [duplicate] - javascript

This question already has answers here:
issue with comparing two numbers in javascript
(5 answers)
Closed 1 year ago.
This code is supposed to give you an equation and when you solve it, you get another one in three seconds. You can choose the amount of equations you're getting and how "high" the math is. And it will give you an alert when you did your chosen amount of questions. This code returns no error but it never gives me the alert as it is supposed to. How do I fix this? (I know I am a beginner so my code is a bit messy)
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " +
Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
var h = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> " +
correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> "
+ correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>

Aside from using strict equality, you're also displaying the correct var before updating the value when it's correct. This should work how you want it:
var rand1, rand2, text1, text2
let count = 0;
let correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
count = count + 1;
correct = correct + 1;
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count == text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<html>
<body>
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>

count is an integer and text2 is a string so the if statement comparing count and text2 will never return true. Therefore that block delivering the alert will never fire.
I would simply use javascript's parstInt function to make sure text2 is an integer
text2 = parseInt(document.getElementById('questions').value);

Related

How do I fix this code regarding getelementbyid [Javascript]?

So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})

My javascript output flashes for a second and then disappears

My Javascript is giving out the right output at the initial glance i get but for some reason the output flashes for a quick second and then disappears
I am not using any frameworks and I am working on basic Javascript.
I've tried checking the console for the output but even there it just flashes. I also tried it on firefox and edge and the same issue arises
function MathRandom2() {
let questionList = [];
questionList.length = 10;
let result = [];
let operator = ['+', '-', '*', '/'];
var numberRand = 0;
// question variable will create the question based off the level choice. numberRand will be the limit.
let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
let total = 0;
var username = document.getElementById("username").value;
//Line 12 to line 37 will check the radio button selection.
if (document.getElementById("beginner").checked) {
let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 10;
} else {
return 0;
}
} else if (document.getElementById("intermediate").checked) {
let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 20;
} else {
return 0;
}
} else if (document.getElementById("advanced").checked) {
let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 100;
} else {
return 0;
}
}
for (let i = 0; i < questionList.length; i++) {
let answer = parseInt(prompt("What is the answer to " + question));
let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span style='background-color: #12CA00'>" + i + "</span>" + "<span style='background-color: #12CA00'> is correct</span>"
let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span style='background-color: #ca0002'>" + i + "</span>" + "<span style='background-color: #ca0002'> is wrong</span>"
if (answer === eval(question)) {
result.push(correct);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
total += 2;
} else {
result.push(wrong);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
}
}
let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
document.getElementById("result").innerHTML = display;
console.log(display);
}
<div id="infoCol_main" class="infoCol_main">
<script src="../Javascript/tute09.js"></script>
<form>
<h1>Welcome</h1>
<fieldset>
<label>Please enter your name here: <br><input type="text" id="username" name="username" required></label><br>
<label>Please choose your difficulty level: <br>
<input type="radio" name="difficulty" id="beginner" value="Beginner" required>Beginner<br>
<input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
<input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
</label>
<div class="buttonHold">
<input type="submit" onclick="MathRandom2()" value="Begin">
</div>
</fieldset>
</form>
</div>
<div>
<p id="result"></p>
</div>
I need it to show a list of answers with the background changed to red or green depending on if the answer was wrong or right respectively. The output is correct and I see it but its only there for a split second before it disappearsenter code here
Use preventDefault()
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
function MathRandom2() {
const form = document.getElementById('form');
form.addEventListener("submit", function(event){
event.preventDefault(); // prevents form from submitting
})
function MathRandom2() {
const form = document.getElementById('form');
form.addEventListener("submit", function(event){
event.preventDefault();
})
let questionList = [];
questionList.length = 10;
let result = [];
let operator = ['+', '-', '*', '/'];
var numberRand = 0;
// question variable will create the question based off the level choice. numberRand will be the limit.
let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
let total = 0;
var username = document.getElementById("username").value;
//Line 12 to line 37 will check the radio button selection.
if (document.getElementById("beginner").checked) {
let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 10;
} else {
return 0;
}
} else if (document.getElementById("intermediate").checked) {
let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 20;
} else {
return 0;
}
} else if (document.getElementById("advanced").checked) {
let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 100;
} else {
return 0;
}
}
for (let i = 0; i < questionList.length; i++) {
let answer = parseInt(prompt("What is the answer to " + question));
let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span style='background-color: #12CA00'>" + i + "</span>" + "<span style='background-color: #12CA00'> is correct</span>"
let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span style='background-color: #ca0002'>" + i + "</span>" + "<span style='background-color: #ca0002'> is wrong</span>"
if (answer === eval(question)) {
result.push(correct);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
total += 2;
} else {
result.push(wrong);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
}
}
let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
document.getElementById("result").innerHTML = display;
}
<div id="infoCol_main" class="infoCol_main">
<script src="../Javascript/tute09.js"></script>
<form id="form">
<h1>Welcome</h1>
<fieldset>
<label>Please enter your name here: <br><input type="text" id="username" name="username" required></label><br>
<label>Please choose your difficulty level: <br>
<input type="radio" name="difficulty" id="beginner" value="Beginner" required>Beginner<br>
<input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
<input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
</label>
<div class="buttonHold">
<input type="submit" onclick="MathRandom2()" value="Begin">
</div>
</fieldset>
</form>
</div>
<div>
<p id="result"></p>
</div>
The default behaviour of the input is to refresh the page once the function has passed. All you need to do is to add this to the top of your function:
function MathRandom2() {
event.preventDefault();
...

Having a problem with my javascript code - computer has to guess the digit value I input

First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check

How can I save best guess (higher/lower)

for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/

Print Multiplication Table

I want to print a multiplication table of user input number. But nothing's happening in the click But what's the mistake? or have I jump into this program early?
<body>
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Process</button>
<br />
<p id="multiply"></p>
<script>
function multFunction() {
var a = document.getElementsById("quest").value;
var i = 1;
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
}
}
</script>
There's a couple of mistakes in your code:
var a = document.getElementsById("quest").value;
Should be:
var a = document.getElementById("quest").value;
// ^ No "s" there.
Next, you don't want to replace the innerHTML each time, you want to add a new row to it, instead. However, writing to innerHTML that often isn't a good idea. (each write to it causes your browser to re-parse the DOM)
Replace:
document.getElementById("multiply").innerHTML = a + "x" + i + "=" + c;
With:
result += a + " x " + i + " = " + c + '</br>';
And add result = ''; at the front of your function. Then, after the loop, write result to the innerHTML
Here's a working demo:
function multFunction() {
var a = document.getElementById("quest").value;
var i = 1;
var result = '';
for (i = 1 ; i < 11 ; i++) {
var c = parseInt(a) * parseInt(i);
result += a + " x " + i + " = " + c + '</br>';
}
document.getElementById("multiply").innerHTML = result;
}
<p>Multiplication table</p>
<input placeholder="Enter the number" type="text" name="number" id="quest"/>
<br />
<button onclick="multFunction()">Enter the number</button>
<br />
<p id="multiply"></p>
Fix getElementsById at the first line in multFunction() it should be
getElementById
using browser console or plugins like Firebug will make it easier for you to catch such errors

Categories

Resources