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!
Related
So my code has all the math done, but when I click the button it uses HTML to add the sums, but I need a popup window with the math on it and that uses javascript. I will send code and screenshots so you are not confused on what it is supposed to look like.
My code:
function sumOfNumbers() {
var theNumber = parseInt(document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var num = 1; num <= theNumber; num++) {
theSum += num;
}
document.getElementById("theSum").innerHTML = "The sum of all the numbers from 1 to " + theNumber + " is " + theSum;
} else {
document.getElementById("theSum").innerHTML = "Enter positive number please!";
}
}
div {
font-size: 16px;
}
<input type="text" id="txtNumber">
<input type="button" value="Calculate Sum" onclick="sumOfNumbers()" />
<br>
<div id="theSum"></div>
Image of what it is supposed to look like:
As you can probably see, when you click the sum button it just has my lettering under it saying how many sums it is, but I need that pop up box to say the sums. Please let me know if anyone can help! Thank you very much.
You need to just replace this
document.getElementById("theSum").innerHTML = "The sum of all the numbers from 1 to " + theNumber + " is " + theSum;
with this
alert("The sum of all the numbers from 1 to " + theNumber + " is " + theSum);
You may do the same for the else part.
Here's a live demo:
function sumOfNumbers() {
var theNumber = parseInt(document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var num = 1; num <= theNumber; num++) {
theSum += num;
}
/** call "laert" to show the result. You may customize the message the way you want */
alert("The sum of all the numbers from 1 to " + theNumber + " is " + theSum);
} else {
alert("Enter positive number please!");
}
}
div {
font-size: 16px;
}
<input type="text" id="txtNumber">
<input type="button" value="Calculate Sum" onclick="sumOfNumbers()" />
<br>
<div id="theSum"></div>
I put my JavaScript inside tags instead of externally(because external files weren't working) and for some reason my code is not running.
Just to be sure that it wasn't a problem with the code itself, I put a simple alert before all the code and nothing popped up.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id = "first" class = "oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type = "text" placeholder = "Enter Kelvin here" id = "kinput">
<button id = "ksubmit">Submit Kelvin</button><br><br>
<textarea id = "fpopup" rows = "5" cols = "50"></textarea>
</div>
<div id = "second" class = "oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type = "text" placeholder = "Enter Fahrenheit here" id = "finput">
<button id = "fsubmit">Submit Fahrenheit</button><br><br>
<textarea id = "kpopup" rows = "5" cols = "50"></textarea>
</div>
<script>
alert("Hello World"); //Testing JS
if(6==6){
alert("ua");
}
function ftok(f){
k = (f − 32) * 5/9 + 273.15;
return k;
}
function ktof(k){
f = (K − 273.15) * 9/5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
</script>
</body>
</html>
You can use DOMContentLoaded function to make sure the HTML is ready and parsed properly. Also you have some syntax errors which i have fixed as well.
Also, You were using some weird minus and multiplication characters.
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed
Your code is now working as expected.
Live Demo:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id="first" class="oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type="text" placeholder="Enter Kelvin here" id="kinput">
<button id="ksubmit">Submit Kelvin</button><br><br>
<textarea id="fpopup" rows="5" cols="50"></textarea>
</div>
<div id="second" class="oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type="text" placeholder="Enter Fahrenheit here" id="finput">
<button id="fsubmit">Submit Fahrenheit</button><br><br>
<textarea id="kpopup" rows="5" cols="50"></textarea>
</div>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
if (6 == 6) {
alert("ua");
}
function ftok(f) {
var k = (f - 32) * 5 / 9 + 273.15;
return k;
}
function ktof(k) {
var f = (k - 273.15) * 9 / 5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
})
</script>
</body>
</html>
Prints '2 x 10 = 20' but not the whole table when the input is 2. I tried various means. But the result is same.
No error. Just like to print the whole multiplication table.
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
document.getElementById("result").value = x + " x " + i + " = " + i * x;
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
You are always changing the value of 'result' rather than adding to it:
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
var result = document.getElementById("result");
var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");
result.appendChild(sum);
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
If I understand what you mean,
You rewrite whole textarea with this code:
document.getElementById("result").value = x + " x " + i + " = " + i * x;
but you need add new result after older results. Something like this:
var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;
Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>
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"/>')