Why when I am submiting an answer javascript is always displaying false? - javascript

I have problem with displaying true/false after submiting an answer to question.
I need to display true when answer is true e.g.( 14+1=15 true), but my code is always displaying false and never displays true.
Hope you will understand my code.
p.s. to display question press answer, in start it doesn't display question.
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 5);
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
var secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
//test answerer
if (testanswer === input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="application/javascript" src="test.js"></script>
</head>
<body>
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="myfunc()">submit</button><br>
<p id="atbilde"></p>
</body>
</html>

First of all, randomizing * 5 for 4 symbols is incorrect. Also, try to compare the answer to the actual numbers, not to the newly generated one.
var last = null;
myfunc();
function myfunc() {
//randomizer + - * /
var symbol;
var s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
var firstnum = Math.floor(Math.random() * 10);
//sec num randomizer
var secnum = Math.floor(Math.random() * 10);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
if (last != null) {
if (last == input && input != '') {
document.getElementById('atbilde').innerHTML = 'true';
} else {
document.getElementById('atbilde').innerHTML = 'false';
}
}
last = testanswer;
}
<form onsubmit="myfunc(); return false">
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="submit">submit</button><br>
<p id="atbilde"></p>
</form>

Need to separate generating questions from checking answers. I modified your code and added some comments:
HTML
<p id="demo"></p>
<input id="input" type="text">
<button id="mybt" type="button" onclick="checkAnswer()">submit</button><br>
<button type="button" onclick="showQuestion()">Show New Question</button><br>
<p id="atbilde"></p>
JavaScript:
var s, firstnum, secnum;
// first, show an initial question for a start
showQuestion();
// this method is used to show initial question and also to "Show New Question" when that button is pressed
function showQuestion(){
//randomizer + - * /
let symbol;
// changed formula to return 1, 2, 3, or 4. It was also returning 0 and 5 previously.
s = Math.floor(Math.random() * 4) + 1;
if (s === 1) {
symbol = '+';
}
if (s === 2) {
symbol = '-';
}
if (s === 3) {
symbol = '*';
}
if (s === 4) {
symbol = '/';
}
//first num randomizer
firstnum = Math.floor(Math.random() * 100);
//sec num randomizer
secnum = Math.floor(Math.random() * 100);
document.getElementById('demo').innerHTML = firstnum + symbol + secnum;
}
// when the user is ready and clicks submit, we check the answer using s, firstnum, and secnum
function checkAnswer() {
//answer filter
var input = document.getElementById('input').value;
var testanswer;
if (s === 1) {
testanswer = firstnum + secnum;
}
if (s === 2) {
testanswer = firstnum - secnum;
}
if (s === 3) {
testanswer = firstnum * secnum;
}
if (s === 4) {
testanswer = firstnum / secnum;
}
console.log('the answer is supposed to be ', testanswer, ' and the user submitted ', testanswer);
//test answer
// I changed === to == this way you can compare a string "100" to the number 100 and it will be true.
// Because "100" === 100 is false (it checks the type) and "100" == 100 is true (does not check the type.)
if (testanswer == input) {
document.getElementById('atbilde').innerHTML = 'true';
}
else {
document.getElementById('atbilde').innerHTML = 'false';
}
}

Related

simple calculator with javascript and it function calculator doesn't apply

I am new to Javascript so this is probably an easy fix but I cannot figure out. I am making a calculator using HTML, CSS and Javascript
and I pretty much only know about declaration, if/else statement, for/while loops and some basic elements of CSS and HTML.
here is my javascript code for the calculator.
var firstNum, operator, previousKey, previousNum;
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const display = document.querySelector('.calculator__display');
function calculate(n1, operator, n2) {
let result = '';
if(operator === '+'){
result = n1 + n2;
}else if(operator === '-'){
result = n1 - n2;
}else if(operator === '*'){
result = n1 * n2;
}else if(operator === '/'){
result = n1 / n2;
}
return result;
}
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
let firstNum = 0;
if (action === 'number') {
if (display.textContent > 0 ) {
display.textContent += buttonContent //
}
else {display.textContent = buttonContent}
//display.textContent = buttonContent
console.log('number1 ' + buttonContent + ' button1');
previousKey = 'number';
}
if (action === 'operator') {
console.log('operator1 ' + buttonContent + ' button1');
operator = buttonContent;
firstNum = display.textContent
//console.log(firstNum)
return firstNum
previousKey = 'operator';
}
if (action === 'decimal') {
// console.log('deciaml1');
previousKey = 'decimal';
}
if (action === 'clear') {
display.textContent = '0'
console.log('clear1');
previousKey = 'clear';
}
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(firstNum, operator, display.textContent)
previousKey = 'calculate';
}
}
});
although I set arithmetic operations above as function calculate(n1, operator, n2)
my caculator // here is what it looks like.
result of 5-9 comes out as -59.
I will appreciate if I could get some help.
thank you in advance.
The issue is that you are sending in strings to the calculate function. So you should explicitly convert the string textContent to integer values as such in your code:
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
previousKey = 'calculate';
}

How to create a reset button for slot machine game in JS

I have a prototype of a slot machine game coded in JS and I am struggling to create a reset button to restart the game. I was trying to create a second function called playAgain where the main game function is called back but it's clearly not working. Maybe I'm supposed to give it a parameter? Not sure. Help please!
const num1 = document.getElementById("num-1");
const num2 = document.getElementById("num-2");
const num3 = document.getElementById("num-3");
const message = document.getElementById("message")
const button = document.getElementById("button");
const random1 = Math.floor(Math.random() * 9) + 1;
const random2 = Math.floor(Math.random() * 9) + 1;
const random3 = Math.floor(Math.random() * 9) + 1;
button.addEventListener("click", checkEquality);
function checkEquality() {
num1.innerHTML = random1;
num2.innerHTML = random2;
num3.innerHTML = random3;
if (random1 === random2 && random1 === random3 && random2 === random3) {
message.innerHTML = "Congratulations, you won!"
} else {
message.innerHTML = "Sorry, you lost!"
}
button.innerHTML = "GIVE IT ANOTHER GO!"
}
button.addEventListener("click", playAgain)
function playAgain() {
if(num1 !== "?" && num2 !== "?" && num3 !== "?") {
message.innerHTML = "";
checkEquality()
}
}
<h1>Slot Machine</h1>
<div>
<p id="num-1">?</p>
<p id="num-2">?</p>
<p id="num-3">?</p>
</div>
<p id="message"></p>
<button id="button">GIVE IT A GO!</button>
You need to put the random numbers inside your function, otherwise you just use the same numbers.
Also if you use const the value can't be changed anymore.
const num1 = document.getElementById("num-1");
const num2 = document.getElementById("num-2");
const num3 = document.getElementById("num-3");
const message = document.getElementById("message")
const button = document.getElementById("button");
button.addEventListener("click", checkEquality);
function checkEquality() {
var random1 = Math.floor(Math.random() * 9) + 1;
var random2 = Math.floor(Math.random() * 9) + 1;
var random3 = Math.floor(Math.random() * 9) + 1;
num1.innerHTML = random1;
num2.innerHTML = random2;
num3.innerHTML = random3;
if (random1 === random2 && random1 === random3 && random2 === random3) {
message.innerHTML = "Congratulations, you won!"
} else {
message.innerHTML = "Sorry, you lost!"
}
button.innerHTML = "GIVE IT ANOTHER GO!"
}
button.addEventListener("click", playAgain)
function playAgain() {
if(num1 !== "?" && num2 !== "?" && num3 !== "?") {
message.innerHTML = "";
checkEquality()
}
}
<html>
<body>
<h1>Slot Machine</h1>
<div>
<p id="num-1">?</p>
<p id="num-2">?</p>
<p id="num-3">?</p>
</div>
<p id="message"></p>
<button id="button">GIVE IT A GO!</button>
<script src="script.js"></script>
</body>
</html>
Maybe the problem is you are using the same button for both of the action.
fix :
button.removeEventListener("click",checkEquality);
button.addEventListener("click",playAgain);
in the check equality..function
and similarly you can do it for playAgain function.

how will I display random math questions from my javascript to my html page but the numbers to be generated are not showing just the signs

I aam trying to create a math game for kids that will ask the player his name and the player to select the level he is playing ,how will I display random math questions from my javascript to my html page but the numbers to be generated are not showing just the signs, this is my script i linked it to my html externally.
here's my code:
var pageName = location.pathname.split("/").slice(-1);
window.addEventListener('load', function () {
alert(pageName);
randomOpr();
pageAction();
});
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
function pageAction() {
if (pageName == "level1.html") {
num1.innerHTML = Math.floor(Math.random() * 20 + 1);
num2.innerHTML = Math.floor(Math.random() * 20 + 1);
} else if (pageName == "level2.html") {
num1.innerHTML = Math.floor(Math.random() * 30 + 21);
num2.innerHTML = Math.floor(Math.random() * 30 + 21);
} else if (pageName == "level3.html") {
num1.innerHTML = Math.floor(Math.random() * 50 + 51);
num2.innerHTML = Math.floor(Math.random() * 50 + 51);
}
}
var operators = ['+', '-', '*', '/']
var selectedOperator = Math.floor(Math.random() * operators.length);
function randomOpr() {
var operator = document.getElementById("opr");
alert((operator).value);
operator.innerHTML = operators[selectedOperator];
}
function checkMath() {
var num1 = parseInt(document.getElementById("num1").innerHTML, 10);
var num2 = parseInt(document.getElementById("num2").innerHTML, 10);
var answer = parseInt(document.getElementById("answer").value, 10);
if (operators[selectedOperator] == "+") {
if (answer === num1 + num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 + num2));
}
} else if (operators[selectedOperator].sign == "-") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 - num2));
}
} else if (operators[selectedOperator].sign == "*") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 * num2));
}
} else if (operators[selectedOperator].sign == "/") {
if (answer === num1 - num2) {
alert("your answer is correct");
} else {
alert(answer + " is incorrect, correct answer is " + (num1 / num2));
}
}
document.getElementById("answer").value = "";
randomNum();
}
Cleaned up the code as suggested in the comments.
No need to get the numbers in the question a second time (already have them when generated).
No need to repeat the answer check and alert code for each operator.
What was 'sign' in 'operators[selectedOperator].sign' in three of the four checks? - removed.
What was randomNum()? - removed.
I'd also check values for the divide questions...
<body>
<div id="num1"></div>
<div id="opr"></div>
<div id="num2"></div>
<div>
<input type=text id="answer">
</div>
<button id="btnAnswer">Check answer</button>
<script>
$(function () {
$("#btnAnswer").click(checkMath)
});
// Set up re-usable variables first.
var pageName = location.pathname.split("/").slice(-1);
var operators = ['+', '-', '*', '/']
var num1 = document.getElementById("num1");
var num2 = document.getElementById("num2");
var answerInput = document.getElementById("answer");
var operator = document.getElementById("opr");
// The values of the numbers to use in the question, current Operator, and calculated answer.
var leftNumber = 0;
var rightNumber = 0;
var selectedOperator = "";
var answer = 0;
window.addEventListener('load', function () {
alert(pageName);
pageAction();
});
function pageAction() {
// Use a switch to perform the check on the level, then set the multiplier.
var multiplier = 0;
switch (pageName) {
case "level1.html":
multiplier = 20;
break;
case "level2.html":
multiplier = 30;
break;
case "level3.html":
multiplier = 50;
break;
default:
multiplier = 20;
break;
}
// Generate the numbers, set them on the page, and get a random Operator.
leftNumber = Math.floor(Math.random() * multiplier + 1);
rightNumber = Math.floor(Math.random() * multiplier + 1);
num1.innerText = leftNumber;
num2.innerText = rightNumber;
answerInput.value = "";
randomOpr();
// Calculate the answer for later use.
switch (selectedOperator) {
case "+":
answer = leftNumber + rightNumber;
break;
case "-":
answer = leftNumber - rightNumber;
break;
case "*":
answer = leftNumber * rightNumber;
break;
case "/":
answer = leftNumber / rightNumber;
break;
default:
answer = leftNumber + rightNumber;
break;
}
}
function randomOpr() {
// Set the current Operator, update the page control.
selectedOperator = operators[Math.floor(Math.random() * operators.length)];
operator.innerText = selectedOperator;
alert((operator).innerText);
}
function checkMath() {
// Check submitted answer against the calculated one, then re-run for another question.
var submittedAnswer = parseInt(answerInput.value, 10);
if (submittedAnswer === answer) {
alert("your answer is correct");
} else {
alert(submittedAnswer + " is incorrect, correct answer is " + answer);
}
pageAction();
}
</script>
</body>

Works while opening but crashes upon reload

So I try to create three values between 1 and 3 that are going to be different every time the page loads. It works perfectly when I open the page the first time, but whenever I try to reload or submit my form the page freeze and it is stuck loading. Any help is much appreciated!
function uniqueAnswerId(){
var rand = (Math.random() * 3.4);
while (Math.round(rand) == 0) {
var rand = (Math.random() * 3.4);
}
return (Math.round(rand));
}
var answerId1 = uniqueAnswerId();
function uniqueAnswerId2(){
var rand2 = (Math.random() * 3.4);
while (answerId1 == Math.round(rand2) || Math.round(rand2) == 0) {
var rand2 = (Math.random() * 3.4);
}
return (Math.round(rand2));
}
var answerId2 = uniqueAnswerId2();
function uniqueAnswerId3(){
var rand3 = (Math.random() * 3.4);
while (answerId1 == Math.round(rand3) || answerId2 == Math.round(rand3)){
while (Math.round(rand3) == 0){
var rand3 = (Math.random() * 3.4);
}
}
return (Math.round(rand3));
}
var answerId3 = uniqueAnswerId3();
console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))
your 3rd while loop should look like this, with another "||" in your condition instead of a whole new while loop.
function uniqueAnswerId3(answerId1, answerId2){
var rand3 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3) || Math.round(rand3)===0){
rand3 = (Math.random() * 3.4);
}
return (Math.round(rand3));
}
I believe you have an infinite loop. Here is the fiddle to fix your code.
Changes: Use '===' instead of '=='
Function Hoisting executes those functions before the variable declarations, which means referencing them inside the functions doesn't work. Added parameters to accept the arguments required.
https://jsfiddle.net/80xdmsjL/
function uniqueAnswerId(){
var rand = (Math.random() * 3.4);
while (Math.round(rand) === 0) {
rand = (Math.random() * 3.4);
}
return (Math.round(rand));
}
var answerId1 = uniqueAnswerId();
function uniqueAnswerId2(answerId1){
var rand2 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand2) || Math.round(rand2) === 0) {
rand2 = (Math.random() * 3.4);
}
return (Math.round(rand2));
}
var answerId2 = uniqueAnswerId2(answerId1);
function uniqueAnswerId3(answerId1, answerId2){
var rand3 = (Math.random() * 3.4);
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
while (Math.round(rand3) === 0){
rand3 = (Math.random() * 3.4);
}
}
return (Math.round(rand3));
}
var answerId3 = uniqueAnswerId3(answerId1, answerId2);
console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))
Take a look at this part of your code:
while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
while (Math.round(rand3) === 0){
rand3 = (Math.random() * 3.4);
}
}
Lets see what happen with the following values:
answerId1 = 1
answerId1 = 2
Math.round(rand3) = 1
in this case, you will have:
while (true){
while(false){
never_executed();
}
}
So it will loop until infinite in the outer 'while'.
To avoid this you could simply do what #Nicholas Bakolias says, add 'another "||" in your condition instead of a whole new while loop'

Round the textbox value javascript

I have a radtextbox with double type mode. And i have set round as 1. So it is giving the result as
20.6 => 20.5
20.7 => 20.5
20.9 => 21.0
But all i need is like this (few samples)
20.6 => 21.0
20.5 => 20.5
20.4 => 20.0
20.29 => 20.0
20.53 => 20.5
20.59 => 21
I tried to fix this by restricting the more than one decimal value. but the code is not working properly.
Code:
<script type="text/javascript">
function GetIndex(sender, args) {
var textbox = $find('<%= CPDPointsTextBox.ClientID %>');
var val = textbox.get_value();
var dsds = val.toString();
if (dsds.indexOf(".") > -1) {
if (dsds.length - (dsds.indexOf(".") + 1) > 1) {
alert(dsds.length - (dsds.indexOf(".") + 1));
args.set_cancel(true);
}
else
return true;
}
else {
if (parseInt(dsds) > 0) {
return true;
}
else
args.set_cancel(true);
}
}
<telerik:RadNumericTextBox ID="CPDPointsTextBox" Width="39px" runat="server" MaxLength="5"
MaxValue="999" MinValue="0">
<NumberFormat DecimalDigits="1" KeepNotRoundedValue="false" />
<ClientEvents OnValueChanged="CPDPointsTextBox_ValueChanged" OnKeyPress="GetIndex" />
</telerik:RadNumericTextBox>
You may use Jquery for this
var num = parseFloat(document.getElementById('textbox').value);
var new_num = Math.round(num).toFixed(2);
try here JsFiddle
I am using the following code. (May be bulkier).
function convertFloatDecimal (num, nDecimal)
{
var s;
if (nDecimal == null)
nDecimal = 1;
if (nDecimal == 1)
{
if (num < 0)
{
num= Math.abs (num);
s = ((Math.round (parseFloat (num) * 10)/10 ) * -1);
}
else
s = (Math.round (parseFloat (num) * 10)/10);
s = s.toString();
if (s.indexOf (".") == -1)
s+= ".0";
}
else if (nDecimal == 2)
{
if (num < 0)
{
num= Math.abs (num);
s = ((Math.round (parseFloat (num) * 100) / 100) * -1);
}
else
s = (Math.round (parseFloat (num) * 100) / 100);
s = s.toString();
if (s.indexOf (".") == -1)
s+= ".00";
if (s.indexOf (".") == s.length-2) // Add leading 0
s+= "0";
}
else if (nDecimal == 0)
{
if (num < 0)
{
num= Math.abs (num);
s = (Math.round (num) * -1);
}
else
s = (Math.round (num));
}
else
{
s = parseInt (s);
}
return s;
}
The following code meets the expectation. Thank you for all your replies.
Code:
function change(lnk, evt) {
var textbox = $find('<%= CPDTextBox.ClientID %>');
var val = lnk.value.toString();
if (val != '') {
if (val.indexOf(".") > -1) {
var values = new Array();
values = val.split(".");
var rouDec = round(parseFloat('.' + values[1]), 1);
if (rouDec > .5) {
val = parseInt(values[0]) + 1;
}
else if (rouDec == .5) {
val = parseInt(values[0]) + .5;
}
}
}
textbox.set_value(val);
}
function round(n, dec) {
n = parseFloat(n);
if (!isNaN(n)) {
if (!dec) var dec = 0;
var factor = Math.pow(10, dec);
return Math.floor(n * factor + ((n * factor * 10) % 10 >= 5 ? 1 : 0)) / factor;
} else {
return n;
}
}

Categories