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.
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 am trying to call a set of elements from an HTML doc by class name, which I understand returns them as an array-like object. I would like to cycle through the values of this array in a for loop, but the loop is returning 'undefined' for every value in the array, even though there is definitely a value in the elements that I am calling.
I basically want to output the following onto the web page, into some simple div elements:
Age prediction line 1: Hello George, you are 28 in 2019
Age prediction line 2: Hello Andy, you are 29 in 2020
Age prediction line 3: Hello Kyle, you are 30 in 2021
Age prediction line 4: Hello Jenny, you are 31 in 2022
The names are the values of the elements in the "myinput" class. I am using a pretty standard for loop as below:
const years = [2019, 2020, 2021, 2022];
var name = document.getElementsByClassName("myinput");
var age = document.getElementById("agefield").value;
var intage = parseInt(age, 10);
for (i = 0; i < 4; i++) {
document.getElementsByClassName("ageprediction")[i].innerHTML = "Age
prediction line " + (i+1) + ": ";
document.getElementsByClassName("testdiv")[i].innerHTML = " Hello " +
name[i].value + " you are " + [intage+i] + " in " + years[i];
}
There is just one agefield element, and calling that by Id, adding.value and converting to an integer works fine. But after understanding and reading everywhere that you could use code like this to cycle through the elements of a getElementbyClass array in a for loop using the current index value, I am still getting 'undefined' as the result. Is this because name[i].value is not the correct code?
UPDATE: A couple of people asked to see the relevant HTML as well, here it is:
<section id="form">
<input class="myinput" value="George"/><br/><br/>
<input class="myinput" value="Andy"/><br/><br/>
<input class="myinput" value="Kyle"/><br/><br/>
<input class="myinput" value="Jenny"/><br/><br/>
<input id="agefield" placeholder="Your age" value="28"/><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
</section>
As you can see, I'm just using predefined values in the inputs for now for testing purposes.
It is actually works. Check out this link : https://jsfiddle.net/dy0feLha
const years = [2019, 2020, 2021, 2022];
var name = document.getElementsByClassName("myinput");
var age = document.getElementById("agefield").value;
var intage = parseInt(age, 10);
for (i = 0; i < 4; i++) {
document.getElementsByClassName("ageprediction")[i].innerHTML = "Age prediction line " + (i+1) + ": ";
document.getElementsByClassName("testdiv")[i].innerHTML = " Hello " +
name[i].value + " you are " + [intage+i] + " in " + years[i];
}
I simply just changed first line in the loop. It has to be in the same line. But it maybe already same in your code editor.
You can't affect content to a variable named "name", the content will be automatically converted to string :
window.name will convert all values to their string representations by
using the toString method.
From developer.mozilla
It works if you simply rename the variable
const years = [2019, 2020, 2021, 2022];
var names = document.getElementsByClassName("myinput");
console.log(names);
var age = document.getElementById("agefield").value;
var intage = parseInt(age, 10);
for (i = 0; i < 4; i++) {
document.getElementsByClassName("ageprediction")[i].innerHTML = "Age prediction line " + (i+1) + ": ";
document.getElementsByClassName("testdiv")[i].innerHTML = " Hello " + names[i].value + " you are " + [intage+i] + " in " + years[i];
}
<section id="form">
<input class="myinput" value="George"/><br/><br/>
<input class="myinput" value="Andy"/><br/><br/>
<input class="myinput" value="Kyle"/><br/><br/>
<input class="myinput" value="Jenny"/><br/><br/>
<input id="agefield" placeholder="Your age" value="28"/><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
<div class ="ageprediction"></div><div class = "testdiv">Testing</div><br/><br/>
</section>
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>
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>
I'm trying to debug a JavaScript in Firefox's debugger, and it won't let me set any breakpoints, and all the step buttons (step into, step out) are grayed out. I also tried Firebug, and I have the exact same results - no breakpoints, step buttons grayed out. What gives? This is my first post here, and I apologize for my messy code here. Anywho, here's my code:
<?xml version - "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Page 452 - Exercise 11.7</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial scale=1.0">
<script>
function buttonClicked() {
var article = ["the", "a", "one", "some", "any"];
var noun = ["boy", "girl", "dog", "town", "car"];
var verb = ["drove", "jumped", "ran", "walked", "skipped"];
var preposition = ["to", "from", "over", "under", "on"];
var story = "Once upon a time, ";
var sentence = "";
alert (sentence);
var output = document.getElementById("textArea");
output.value = "";
for (var i=0; i<=3; i++){
sentence += article[Math.floor(Math.random()*article.length)] + " ";
alert(sentence.charAt(0));
alert("Story is " + story);
/* if (charAt(sentence[0-3]) == ".") {
sentence +=
} */
sentence += noun[Math.floor(Math.random()*noun.length)] + " ";
sentence += verb[Math.floor(Math.random()*verb.length)] + " ";
sentence +=
preposition[Math.floor(Math.random()*preposition.length)] + " ";
sentence += article[Math.floor(Math.random()*article.length)] + " ";
sentence += noun[Math.floor(Math.random()*noun.length)] + ". ";
story += sentence;
output.value = story;
window.alert (sentence);
window.alert (story);
// sentence ="";
}
story += "THE END";
// output.value = sentence;
}
</script>
</head>
<body>
<p>Click the button for a funny story!<br/>
<input type="button" id="go" onclick="buttonClicked()" value="Go!"/><br/></p>
<textarea id="textArea" rows="10" cols="30"></textarea>
</body>
</html>