Number of guess in multiplication quiz - javascript

I' ve been stuck on a problem for a while and I need your help.
So I am trying to make a multiplication game that is asking a user for an answer so long until he puts 'x' as an answer. (so x is the only answer to end the game). And also the game needs guess counter so when the game finishes the site puts out how many answers were correct and how many were inccorrect and he also get the percantage of succes.
thanks for the help.
<html>
<head>
</head>
<title> Preizkusi svoje znanje poštevanke! </title>
<body>
<p> Pozdravljeni, ste pripravljeni preizkusiti svoje znanje poštevanke?</p>
<script type="text/javascript">
// ime datoteke:avto.html
// avtor:Matic Molka
//Program, ki izbere naključni števili med 1 in 10 ter uporabnika vpraša po njunem zmnožku ter preveri pravilnost uporabnikovega odgovora
//Vhodni podatki: naključni števili, ki jih zgenerira računalnik in uporabnikov odgovor
//Izhodni podatki: uporabniku vrne odgovor glede na to ali je odgovor pravilen (čestitamo) ali napačen (narobe)
//Deklariramo in inicializiramo spremenljivke in preverimo njihovo delovanje
var nakljucna_st1 = Math.floor(Math.random() * 10);
//document.write('<p>'+ nakljucna_st1 + '</p>');
var nakljucna_st2 = Math.floor(Math.random() * 10);
//document.write('<p>'+ nakljucna_st2 + '</p>');
var zmnožek = nakljucna_st1 * nakljucna_st2
//document.write('<p>'+ zmnožek + '</p>'); // to je rezultat (zmnožek) prve in druge naključne stevilke
var odgovor = prompt('Koliko je zmnožek ' + nakljucna_st1 + ' in ' + nakljucna_st2 + '?');
if(zmnožek == odgovor){
document.write('<font color="green"><h1>Čestitamo!</h1></font>');
}
else{
document.write('<font color="red"><h1>Napačno!</h1></font>');
}
</script>
</body>
</html>

Related

Array reading as undefined/0 in JS

I'm trying to make a madlib type website and I'm storing the input values from the text boxes into an array using a for loop. Its giving me the error as followed:
script.js:67 Uncaught ReferenceError: madLibAnswers is not defined
at submitButtonOnClick (script.js:67:92)
at HTMLButtonElement.onclick (VM147 madlib.html:14:76)
JAvascript
/*
__ _______ ___ _____ ___ ____
/ |/ / __ \ / | / ___// | / __ \
/ /|_/ / /_/ / / /| | \__ \/ /| | / / / /
/ / / / _, _/ / ___ |___/ / ___ |/ /_/ /
/_/ /_/_/ |_(_) /_/ |_/____/_/ |_/_____/
RUN THIS PROGRAM IN A SEPERATE BROWSER (hit the arrow in top right of the webview)
REPLIT DOESNT SUPPORT BROSWER HASHES/FRAGMENTS
*/
/* List that the answers save to */
/* Current madlib that the page is currently on */
var currentLib;
/* Number of words into the Madlib */
// Zoo Madlib text
var madLibZooTypes = ["Adjective", "Noun", "Verb, Past tense", "Adverb", "Adjevtive", "Noun", "Noun", "Adjective", "Verb", "Adverb", "Verb Past tense", "Adjective"]
var madLibParkTypes = ["Adjective", "Plural Noun", "Noun", "Adverb", "Number", "Verb, Past Tense", "-est Adjective", "Verb, Past Tense", "Adverb", "Adjective"]
var madLibArcadeTypes = ["Plural Noun", "Plural Noun", "Verb", "Noun", "-ing Verb", "Plural Noun", "Noun", "Plural Noun"]
function loadURLFragments() {
currentLib = window.location.hash.substring(1)
if (currentLib == "selected=zoo") {
for (let i = 0; i < 12; i++) {
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<label id="javascriptInsertTextbox' + i + '"></label>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<input type="text" id="input' + i + '">');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('javascriptInsertTextbox' + i).innerHTML = madLibZooTypes[i];
}
} else if (currentLib == "selected=park") {
for (let i = 0; i < 10; i++) {
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<label id="javascriptInsertTextbox' + i + '"></label>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<input type="text" id="input' + i + '">');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('javascriptInsertTextbox' + i).innerHTML = madLibParkTypes[i];
}
} else if (currentLib == "selected=arcade") {
for (let i = 0; i < 8; i++) {
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<label id="javascriptInsertTextbox' + i + '"></label>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<input type="text" id="input' + i + '">');
document.getElementById('centerItems').insertAdjacentHTML('beforebegin', '<br>');
document.getElementById('javascriptInsertTextbox' + i).innerHTML = madLibArcadeTypes[i];
}
}
}
/* Zoo Madlib */
function submitButtonOnClick() {
/* Park Madlib */
if (currentLib = "selected=zoo") {
for (let i = 0; i > 12; i++) {
madLibAnswers[i] = document.getElementById('input' + i).value
console.log("madLibAnswerswer: ", madLibAnswers[i])
}
console.log("currentLib: ", currentLib);
console.log("madLibZooTypes: ", madLibZooTypes);
console.log("submitButton: ", document.getElementById("submitButton"));
document.getElementById('typeOfWord').innerHTML = `Today I went to the zoo. I saw a(n) ${madLibAnswers[0]}/* adjective */ + " " + ${madLibAnswers[1]}/*(Noun)*/ + " jumping up and down in its tree. He ${madLibAnswers[2]}/*(verb, past tense)*/ + " ${madLibAnswers[3]}/*(adverb)*/ + " through the large tunnel that led to its ${madLibAnswers[4]}/*(adjective)*/ + " ${madLibAnswers[5]}/*(noun)*/ + ". I got some peanuts and passed them through the cage to a gigantic gray ${madLibAnswers[6]}/*(noun)*/ + " towering above my head. Feeding that animal made me hungry. I went to get a ${madLibAnswers[7]}/*(adjective)*/ + " scoop of ice cream. It filled my stomach. Afterwards I had to ${madLibAnswers[8]}/*(verb) */ + " ${madLibAnswers[9]}/*(adverb)*/ + " to catch our bus. When I got home I ${madLibAnswers[10]}/*(verb, past tense)*/ + " my mom for a ${madLibAnswers[11]}/*(adjective)*/ + " day at the zoo."`;
}
else if (currentLib = "selected=park") {
for (let i = 0; i > 10; i++) {
madLibAnswers[i] = document.getElementById('input' + i).value
console.log("madLibAnswerswer: ", madLibAnswers[i])
}
console.log("currentLib: ", currentLib);
console.log("madLibZooTypes: ", madLibZooTypes);
console.log("submitButton: ", document.getElementById("submitButton"));
document.getElementById('typeOfWord').innerHTML = `Today, my fabulous camp group went to a (an) ${madLibAnswers[0]}/*adjective*/ amusement park. It was a fun park with lots of cool ${madLibAnswers[1]}/*plural noun*/ and enjoyable play structures. When we got there, my kind counselor shouted loudly, 'Everybody off the' ${madLibAnswers[2]}/*noun*/ . We all pushed out in a terrible hurry. My counselor handed out yellow tickets, and we scurried in. I was so excited! I couldn't figure out what exciting thing to do first. I saw a scary roller coaster I really liked so, I ${madLibAnswers[3]}/* adverb */ ran over to get in the long line that had about ${madLibAnswers[4]}/*number*/ people in it. When I finally got on the roller coaster I was ${madLibAnswers[5]}/*past tense verb*/ . In fact I was so nervous my two knees were knocking together. This was the ${madLibAnswers[6]}/*-est adjective*/ ride I had ever been on! In about two minutes I heard the crank and grinding of the gears. That’s when the ride began! When I got to the bottom, I was a little ${madLibAnswers[7]}/*past tense verb*/ but I was proud of myself. The rest of the day went ${madLibAnswers[8]}/*adverb*/ . It was a(an) ${madLibAnswers[9]}/adjective/ day at the fun park.`;
}
else if (currentLib = "selected=arcade") {
for (let i = 0; i > 8; i++) {
madLibAnswers[i] = document.getElementById('input' + i).value
console.log("madLibAnswerswer: ", madLibAnswers[i])
}
console.log("currentLib: ", currentLib);
console.log("madLibZooTypes: ", madLibZooTypes);
console.log("submitButton: ", document.getElementById("submitButton"));
document.getElementById('typeOfWord').innerHTML = `When I go to the arcade with my ${madLibAnswers[0]}/*plural noun*/ there are lots of games to play. I spend lots of time there with my friends. In the game X-Men you can be different ${madLibAnswers[1]}/*plural noun*/ . The point of the game is to ${madLibAnswers[2]}/*verb*/ every robot. You also need to save people. Then you can go to the next level. In the game Star Wars you are Luke Skywalker and you try to destroy every ${madLibAnswers[3]}/*noun*/ . In a car racing/motorcycle racing game you need to beat every computerized vehicle that you are ${madLibAnswers[4]}/*-ing verb*/ against. There are a whole lot of other cool games. When you play some games you win ${madLibAnswers[5]}/*plural noun*/ for certain scores. Once you're done you can cash in your tickets to get a big ${madLibAnswers[6]}/*noun*/ . You can save your ${madLibAnswers[7]}/*plural noun*/ for another time. When I went to this arcade I didn't believe how much fun it would be. So far I have had a lot of fun every time I've been to this great arcade!`;
}
}
function logStuff() {
for (let i = 0; i < 10; i++)
console.log('rah')
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="loadURLFragments()">
<div id="centerDiv">
<center id="centerItems">
<button id="submitButton" onclick="submitButtonOnClick()" type="button"> Submit </button>
<br>
<button id="consoleLog" onclick="logStuff()" type="button"> buton</button>
<p id="typeOfWord"></p>
<br>
</center>
<br>
<br>
<h1 id="titleHeader"> </h1>
<br>
<br>
<label id="fulltext">
</div>
<script src="script.js"></script>
</body>
</html>
I've tried moving the story variables around cause I find that JS scopes are a bit funky, i've tried making it a separate function. It just hasn't been working for me. All result in the same error but different line number(if I moved it) Worst comes worst I can just do all of it without the for loop and put it in manually but I really want to get this working. Sorry if im doing any bad practices im relatively new to programming.

Extracting information from database using JSON and AJAX

I'm trying to make a simple "search" box using Javascript, AJAX, php and JSON. For this project, I'm just using the database "world" I downloaded from mqsql website.
I'm running into a problem when trying to extract the information from my database. It just takes the first line of information and then I get this
error: "SCRIPT5007: SCRIPT5007: Unable to get property 'Continent' of undefined or null reference
ajaj.js (65,3)"
Thanks in advance for any help you are able to give me!
Here is my ajaj.js code:
var ajaxRequest=new XMLHttpRequest();
var input;
var button;
function init(){
input = document.getElementById('search');
input.addEventListener("keyup", sendRequest, false);
button = document.getElementById('sendButton');
button.addEventListener("click", sendSecondRequest, false);
}
function sendRequest(){
ajaxRequest.onreadystatechange = getRequest;
var searchTxt = "country=" + input.value;
ajaxRequest.open("GET", "getCountries.php?" + searchTxt, true);
ajaxRequest.send();
}
function getRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
var jsonObj = JSON.parse(ajaxRequest.responseText);
var dataList = document.getElementById('countries');
dataList.innerHTML="";
for(var i = 0; i<jsonObj.length; i++){
var option = document.createElement('option');
option.value = jsonObj[i]['Name'];
dataList.appendChild(option);
}
}
}
function sendSecondRequest(){
ajaxRequest.onreadystatechange = getSecondRequest;
var infoCountry = "country=" + input.value;
ajaxRequest.open("GET", "getCountries2.php?" + infoCountry, true);
ajaxRequest.send();
}
function getSecondRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
alert(ajaxRequest.responseText);
var jsonObj2 = JSON.parse(ajaxRequest.responseText);
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
}
}
window.addEventListener("load",init,false);
It's here where the problem lies, I just don't know how to get it to work:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
I've tried a few different solutions but I can't get it working, I've tried to combine the code into one line using:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>" + "Continent: " + jsonObj2[2]["Continent] + "<br>";
but that doesn't seem to work for me either.
Rest of my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<script type="text/javascript" src="ajaj.js"></script>
</head>
<body>
<h1>Sök information om ett land</h1>
<input type="text" list="countries" id = 'search' placeholder="Land">
<datalist id="countries">
</datalist>
<button type="button" id="sendButton">Hämta information</button>
<p id="result"></p>
<p id="result2"></p>
<p id="result3"></p>
</body>
</html>
getCountries.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country%"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
getCountries2.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
db.inc.php
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'Abc12345');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'world');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
$db = new PDO($dsn, DB_USER, DB_PASSWORD);
?>
EDIT: I just got the answer from the comments, the information is on the same row, not different, therefore it didn't work with
jsonObj2[2]["Continent"]
but it did work with
jsonObj2[0]["Continent"]
Thank you #sean!
It means that jsonObj2[2] isnt object. It seems like you dont have 3 rows (jsonObj2[2]) in database return array.
Try
jsonObj2[0]["Code"] + jsonObj2[0]["Continent"] + sonObj2[0]
["Population"]
It should work but dont know why you target to rows 0,2,7.

javascript display multiple images

Just to let you know I am a complete newbie,
I have a html page that shows different images combined. I am using javascript to select images to display.
Here's my code:
<head>
<script type="text/javascript">
var num1 = Math.ceil( Math.random() * 6 );
var num2 = Math.ceil( Math.random() * 6 );
var num3 = Math.ceil( Math.random() * 6 );
var num4 = Math.ceil( Math.random() * 6 );
var num5 = Math.ceil( Math.random() * 4 );
var imgpath1 = "<img src=" + '"' ;
var imgpath2= "./Nums24-38/Nums" + num5 + "_";
var imgpath3= ".png" + '"' ;
var imgpathA = imgpath1 + imgpath2 + num1 + imgpath3 ;
var imgpathB = imgpath1 + imgpath2 + num2 + imgpath3 ;
var imgpathC = imgpath1 + imgpath2 + num3 + imgpath3 ;
var imgpathD = imgpath1 + imgpath2 + num4 + imgpath3 ;
var imgpathE = imgpathA + imgpathB + imgpathC + imgpathD ;
</script>
</head>
<body>
<h1>Hello </h1>
<h2>Welcome to Home-brewed Captcha </h2>
My Random number is <script>document.write(num1); document.write(num2); document.write(num3);document.write(num4)</script>
<p> My path is <script>document.write(imgpath2); document.write(num1); document.write(imgpath3) </script></p>
<p>First Java Image is <script>document.write(imgpathA) </script> </p>
<p>Second Java Image is <script>document.write(imgpathB) </script> </p>
<p>Third Java Image is <script>document.write(imgpathC) </script> </p>
<p>Fourth Java Image is <script>document.write(imgpathD) </script> </p>
<p> Merged Java Image ABCD is
<script> document.write(imgpathA) </script>
<script> document.write(imgpathB) </script>
<script> document.write(imgpathC) </script>
<script> document.write(imgpathD) </script>
</p>
<p> New merged Java image A+B+C+D is<script>document.write(imgpathE) </script> </p>
<h3>Another merge , this time bypassing java <img src="./Nums24-38/Nums3_3.png"><img src="./Nums24-38/Nums3_1.png"><img src="./Nums24-38/Nums3_0.png"><img src="./Nums24-38/Nums3_6.png"></h3>
</body>
You can see a live demo at http://sopariwala.ca/1.html
Why does all images dont show up.
Where am I going wrong.
Muja
Simple... You are using document.write() incorrectly!
str = 'abcd.png'
dcument.write(str)
// result is:
// abcd.png
All you are doing is 'writing' the url of the image to the page.
Try this if you must, though I don't reccomend it over inserting the tags outright:
document.write('<img src="abcd.png"/>')

How do I execute an onclick event within document.write in Javascript?

Good evening!
I am making a Javascript auto-generated calendar for a school assignment. The basic creation has succeeded, but the next assignment is to be able to add appointments into the calendar by pressing a "day".
This is where my problem starts. I made a simple function and tried adding that function as an onclick event to my elements being generated, as you can see in my code below.
Problem is that when I click an element, nothing happens! I tried using a dummy function like alert("it worked"), but still no result.
Can anyone help me with this question?
My code:
HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="kalender.js"></script>
<title>Auto-gen kalender</title>
<style type="text/css">
.td, tr
{
border-color: red;
border-width: 5px;
font-family:'Bookman Old Style';
}
.table
{
background-color: grey;
color: darkred;
}
.body
{
background-color: lightgray;
}
</style>
</head>
<body>
</body>
</html>
Javascript:
// HOW
function MaakAfspraak() {
alert("afspraak gemaakt");
}
function Dag_Titel(dag_naam)
{
document.write("<td width=40>" + dag_naam + "</td>");
}
function VulTabel(maand, maand_length)
{
dag = 1;
//beginnen met tabel + berg vars, dag hieboven is belangrijk
document.write("<table border=5 cellspacing=3 cellpadding=%3><tr>");
document.write("<td align=center colspan=7><b>" + maand + " " + jaar + "</b><tr>");
Dag_Titel("Zo");
Dag_Titel("Ma");
Dag_Titel("Di");
Dag_Titel("Wo");
Dag_Titel("Do");
Dag_Titel("Vr");
Dag_Titel("Za");
// dit zijn de lege cellen voor het begin van een maand
document.write("</tr><tr>")
for (var i=1; i<start_dag; i++)
{
document.write("<td onclick=´MaakAfspraak()´>");
}
// 1ste week van een maand
for (var i=start_dag; i < 8; i++)
{
document.write("<td align=center onclick=´MaakAfspraak()´>" + dag + "</td>");
dag++;
}
document.write("<tr>");
// rest van de weken
while (dag <= maand_length)
{
for (var i = 1; i <= 7 && dag <= maand_length; i++)
{
document.write("<td align=center onclick=´MaakAfspraak()´>" + dag + "</td>");
dag++;
}
document.write("</tr><tr>")
// hieronder de 1ste dag voor de volgende maand zodat we alles kunnen vullen
start_dag = i;
}
document.write("</tr></table></ br>")
}
// eerste dag van nieuwe jaar en meer shiz
jaar = 2014;
vandaag = new Date("Januari 1, " + 2014)
start_dag = vandaag.getDay() + 1;
VulTabel("Januari", 31);
VulTabel("Februari", 29);
VulTabel("Maart", 31);
VulTabel("April", 30);
VulTabel("Mei", 31);
VulTabel("Juni", 30);
VulTabel("Juli", 31);
VulTabel("Augustus", 31);
VulTabel("September", 30);
VulTabel("Oktober", 31);
VulTabel("November", 30);
VulTabel("December", 31);
//end
Turns out I was using the wrong type of qoutes for my onclick function call. Thanks #KevinB!
Don't use document.write. Instead, create your elements using the DOM (which is much faster) and then add the event via addEventListener:
//Create it
var td = document.createElement( "td" );
//Add to tr
tr.appendChild( td );
//Add event
td.addEventListener( "click", MaakAfspraak, false );

JavaScript Multiplication Game

I am supposed to make this simple program. It produces a multiplication problem, and when the user types the correct answer, it is supposed to produce another question. Instead it goes into an infinite loop and never stops, the answer field and the button go away. Also, I am supposed to make the comment about the users answer, one of 4 different sayings. Without using Arrays how would I do that?
My professor is no help, really getting aggravated as I have no where else to turn.
<html>
<title>HW 9.27 and 9.28</title>
<head>
<script type="text/javascript">
var number1;
var number2;
var answer3;
var answer2;
function problem() {
number1 = Math.floor(1 + Math.random() * 9);
number2 = Math.floor(1 + Math.random() * 9);
document.writeln("How much is " + number1 + " times " + number2 + " ?");
answer2 = (number1 * number2);
}
function answer1() {
var statusDiv = document.getElementById("status");
answer3 = document.getElementById("answer").value;
if (answer3 != answer2) statusDiv.innerHTML = "No. Please try again";
else if (answer3 == answer2) {
statusDiv.innerHTML = "Very good!";
problem();
}
}
problem();
</script>
</head>
<body>
<form>
<input id="answer" type="text" />
<input type="button" value="Solve!" onclick="answer1()" />
<div id ="status">Click the Solve button to Solve the problem</div>
</form>
</body>
</html>
simply put, document.writeln("How much is " + number1 + " times " + number2 + " ?"); erases all content on the then writes the string. So you're loosing all your form inputs.
The reason it doesn't happen on the initial page load is because the call to document.writeln happens before the form elements load.
Try this:
<html>
<title>HW 9.27 and 9.28</title>
<head>
<script type="text/javascript">
var number1;
var number2;
var answer3;
var answer2;
function problem()
{
number1 = Math.floor( 1 + Math.random() * 9 );
number2 = Math.floor( 1 + Math.random() * 9 );
document.getElementById("prompt").innerHTML = "How much is " + number1 + " times " + number2 + " ?";
answer2 = (number1*number2);
}
function answer1()
{
var statusDiv = document.getElementById("status");
answer3=document.getElementById("answer").value;
if(answer3 != answer2)
statusDiv.innerHTML="No. Please try again";
else
if (answer3==answer2)
{
statusDiv.innerHTML="Very good!";
problem();
}}
</script>
</head>
<body onload="problem();">
<form>
<div id ="prompt"></div>
<input id="answer" type="text" />
<input type="button" value="Solve!" onclick="answer1()" />
<div id ="status">Click the Solve button to Solve the problem</div>
</form>
</body>
</html>
There is no infinite loop, but document.writeln causes problems.
I suggest you set the question the same way as you set the other messages.
I think the problem is with the document.writeln.
You have a div for the question instead and then assing the question as innerHTMl to that div.
Try this:
<html>
<title>HW 9.27 and 9.28</title>
<head>
<script type="text/javascript">
var number1;
var number2;
var answer3;
var answer2;
function problem()
{
number1 = Math.floor( 1 + Math.random() * 9 );
number2 = Math.floor( 1 + Math.random() * 9 );
var question = document.getElementById("question");
question.innerHTML = "How much is " + number1 + " times " + number2 + " ?";
answer2 = (number1*number2);
}
function answer1()
{
var statusDiv = document.getElementById("status");
answer3=document.getElementById("answer").value;
if(answer3 != answer2)
statusDiv.innerHTML="No. Please try again";
else
if (answer3==answer2)
{
statusDiv.innerHTML="Very good!";
document.getElementById("answer").value = "";
problem();
}
}
</script>
</head>
<body>
<form>
<div id ="question"></div>
<input id="answer" type="text" />
<input type="button" value="Solve!" onclick="answer1()" />
<div id ="status">Click the Solve button to Solve the problem</div>
</form>
<script type="text/javascript">
problem();
</script>
</body>
</html>
You have a few issues:
First of all when you click the Solve button your answer1 function is not getting called.
I recommend not using onclick in HTML, but adding:
document.getElementById("solve").onclick = answer1;
to your JavaScript.
Also, you're comparing String input to a number. That's not going to work. You need to convert the input to a Number. Use parseInt(answer3,10) the 10 means base 10, and will make sure that 06 is interpreted as 6 instead of as an octal.
Also I would not use if and then else if. Just use if and then else so:
if (parseInt(answer3,10) === answer2){
//got it right!
}
else {
///got it wrong
}
Also don't use document.writeln. It's erasing stuff on your page. Create a div: <div id="problem"></div> and fill it with:
problemDiv.innerHTML = "How much is " + number1 + " times " + number2 + " ?";
You should also rename your variables. Your variable names are ambiguous.
Good luck!
Stuff to read:
Learn about parseInt
Why not to use document.write
The proper way to attach event handlers
Try it out!

Categories

Resources