How to save multiple user inputs into new variables - javascript

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);

Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/

You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

Related

Draw in two tables vanilla JS

I am working with program that will randomly choose who is making a Christmas gift to whom.
I've created an empty array. When you add a "player" it's pushing the name into two different arrays. Players[] and Players2[].
When you start a draw. The program writes the names of the Players[] on the left hand side and on the right side it writes the drawn names from Players2[].
Every Player from Players2[], after being drawn, is being deleted from the array so in the end we have an empty Players2[] array and full Players[] array.
The problem is: I can't make a working if statement that is checking if the person will not draw himself...
let Players = [];
let Players2 = [];
const addBTN = document.getElementById('addBTN');
const onlyLetters = /^[a-zżźćóęśńłA-ZŻŹĆÓŁĘŚŃŁ ]+$/;
const refreshBTN = document.getElementById('refreshBTN');
const warningBTNyes = document.getElementById('warning-button-yes');
const warningBTNno = document.getElementById('warning-button-no');
const playersList = document.getElementById('playersList');
const playersList2 = document.getElementById('playersList2');
const startBTN = document.getElementById('startBTN');
const drawLotsBTN = document.getElementById('drawLotsBTN');
addBTN.addEventListener('click', function() {
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
console.log('error_empty_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Wpisz imię osoby!";
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Dodaj kolejną osobę.";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
});
refreshBTN.addEventListener('click', function() {
document.getElementById('warning').style.display = "block";
});
warningBTNyes.addEventListener('click', function() {
location.reload(true);
document.getElementById('addPLAYER').value = "";
});
warningBTNno.addEventListener('click', function() {
document.getElementById('warning').style.display = "none";
});
startBTN.addEventListener('click', function() {
drawLotsBTN.disabled = false;
const input = document.getElementById('addPLAYER');
const person = document.getElementById('addPLAYER').value;
if (input.value == "") {
} else if (input.value.match(onlyLetters)) {
console.log('good');
Players.push(person);
Players2.push(person);
playersList.innerHTML = playersList.innerHTML + "<br>" + person;
document.getElementById('addPLAYER').value = "";
document.getElementById('errorMSG').style.color = "green";
document.getElementById('errorMSG').innerHTML = "Powodzenie! Zaczynasz losowanie!";
} else {
console.log('error_input');
document.getElementById('errorMSG').style.color = "red";
document.getElementById('errorMSG').innerHTML = "Coś jest nie tak z imieniem. Pamiętaj aby wprowadzać same litery!";
}
document.getElementById('addPLAYER').disabled = true;
});
drawLotsBTN.addEventListener('click', function() {
for (let i = 0; i = Players2.length; i++) {
if (Players2.length > 0) {
randomPerson = Math.floor(Math.random() * Players2.length);
if (randomPerson != Players.indexOf(i)) {
console.log(Players2[randomPerson]);
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players2[randomPerson];
Players2.splice(randomPerson, 1);
}
} else {
console.log('error_empty_array');
}
}
});
<div id="warning" class="warning">
<div class="warning-flex">
<h1>Wszelkie wpisane imiona zostaną usunięte</h1>
<div class="warning-buttons">
<button id="warning-button-yes" class="warning-button-yes">Tak</button>
<button id="warning-button-no" class="warning-button no">Nie</button>
</div>
</div>
</div>
<div class="lotteryContainer">
<div class="left">
<p>dodaj osobę</p>
<div class="addPerson">
<input required id="addPLAYER" type="text">
<button id="addBTN">+</button>
<p id="errorMSG"></p>
<div class="refresh">
<button id="refreshBTN">Od nowa</button>
<button id="startBTN">Start</button>
</div>
</div>
</div>
<div class="right">
<p>Uczestnicy</p>
<div class="tables">
<div class="tableLeft">
<p id=playersList></p>
</div>
<div class="tableRight">
<p id="playersList2"></p>
</div>
</div>
<button id="drawLotsBTN">Losuj</button>
</div>
</div>
<script src="app.js"></script>
Now if I understand what your program aims to do, there is a simple algorithm for it.
How I understand your goal:
You have a list of persons who are going to give presents to each other. (like in secret Santa). It is random who will give to who, but each person gives and receives one gift.
How to implement it (i'd normaly use maps, but I am guessing you are more comfortable with arrays):
players = ["Adam", "Bret", "Clay", "Donald"];
players.sort(function(a, b){return 0.5 - Math.random()}); // shuffles array
gives_to = [...players]; // copy values of array
gives_to.push(gives_to.shift()); // let the first element be the last
Here the first player (players[0]) will give to gives_to[0] and the second to gives_to[1] etc.
I've created this JS script trying to use Trygve Ruud algorithm but it doesn't work like desired.
drawLotsBTN.addEventListener('click', function(){
if(Players.length > 0) {
console.log(Players)
Players.sort(function(a, b){
return 0.5 - Math.random();
});
for(let i = 0; i < Players.length; i++){
playersList2.innerHTML = playersList2.innerHTML + "<br>" + Players[i];
}
}
else{
console.log('error_empty_array');
}
});

All buttons only affect one input instead of respective input

I am making a little project for my self. So basically its main function is to create a base counter for each game.
For example: If there are two players it should create three bases. (This is for the card game "smash up" if that helps you understand better.) But when the Buttons populate they all only effect the last input. I can not figure out how to make them effect their respective inputs.
The problem I am having is that every button I click only effects the last input.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type = "text" placeholder = "How many players?">
<button id = "enter" onclick = "baseMaker()">
Enter
</button>
</div>
<p></p>
</body>
</html>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function baseMaker()
{
for(var i = 0; i <= input.value; i++)
{
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement( "input");
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
This is a common thing to run into especially when not using a framework in javascript.
I am not sure why this happens but when a function is defined directly in a loop, the closure for these created functions becomes whatever it is after the last iteration. I believe it is because the closure for each callback function is only "sealed up" (for lack of a better word) at the end of the loop-containing-function's execution which is after the last iteration. It's really beyond me, though.
There are some easy ways to avoid this behavior:
use bind to ensure a callback gets called with the correct input (used in solution at bottom)
create a function which creates a handler function for you and use that in the loop body
function createIncrementHandler(input, howMuch){
return () => input.valueAsNumber += howMuch;
}
/// then in your loop body:
downButton.addEventListener('click', createIncrementHandler(score, 1));
get the correct input by using the event parameter in the handler
downButton.addEventListener('click', (event) => event.target.valueAsNumber += 1);
make the entire body of the loop into a function, for example:
function createInputs(i) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
Here is a full example of one of the possible fixes.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type="text" placeholder="How many players?">
<button id="enter" onclick="baseMaker()">
Enter
</button>
</div>
<p></p>
<script>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function incrementInput(input, byHowMuch) {
input.valueAsNumber = input.valueAsNumber + byHowMuch;
}
function baseMaker() {
for (var i = 0; i <= input.value; i++) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement("button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', incrementInput.bind(null, score, 1));
//downbutton
var downButton = document.createElement("button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', incrementInput.bind(null, score, -1));
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
</script>
</body>
</html>
I will do that this way :
const
AllBases = document.querySelector('#bases')
, bt_Start = document.querySelector('#game-go')
, bt_newGame = document.querySelector('#new-game')
, playerCount = document.querySelector("#play-start > input")
;
playerCount.value = ''
playerCount.focus()
playerCount.oninput = () =>
{
playerCount.value.trim()
bt_Start.disabled = (playerCount.value === '' || isNaN(playerCount.value))
playerCount.value = (bt_Start.disabled) ? ''
: (playerCount.valueAsNumber > playerCount.max) ? playerCount.max
: (playerCount.valueAsNumber < playerCount.min) ? playerCount.min
: playerCount.value
}
bt_newGame.onclick = () =>
{
playerCount.value = ''
playerCount.disabled = false
bt_Start.disabled = true
bt_newGame.disabled = true
AllBases.innerHTML = ''
playerCount.focus()
}
bt_Start.onclick = () =>
{
playerCount.disabled = true
bt_Start.disabled = true
bt_newGame.disabled = false
for(let i = 0; i <= playerCount.valueAsNumber; i++)
{
let base = document.createElement('p')
base.countValue = 20 // create a counter property on <p>
base.innerHTML = `Base ${i+1} : <span>${base.countValue}</span> <button>+</button> <button>−</button>\n`
AllBases.appendChild(base)
}
}
AllBases.onclick = ({target}) =>
{
if (!target.matches('button')) return // verify clicked element
let countElm = target.closest('p')
if (target.textContent==='+') countElm.countValue++
else countElm.countValue--
countElm.querySelector('span').textContent = countElm.countValue
}
#bases p span {
display : inline-block;
width : 6em;
border-bottom : 2px solid aqua;
padding-right : .2em;
text-align : right;
margin : 0 .3em;
}
#bases p button {
width : 2em;
margin : 0 .1em;
cursor : pointer;
}
<hr>
<hl> Score Keeper </h1>
<hr>
<div id="play-start" >
<input type="number" placeholder="How many players?" min="2" max="4">
<button id="game-go" disabled> Enter </button>
<button id="new-game" disabled> new </button>
</div>
<hr>
<div id="bases"></div>
If it helps, I can add more explanations

Javascript textcontent is not displaying anything

I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.

Web page text on mobile increasing in size when it receives a message from our mqtt broker

When I get a message from our mqtt broker, the text on my mobile web page increases and I have no idea why it is doing it. Please help. Look for yourself. Sorry for how messy it is; I am new to coding.
<!DOCTYPE html>
<html>
<body>
<style>
.myClass {
color: black;
background-color: white;
text-align: left;
margin: auto;
font-size: auto;
width: auto;
}
</style>
<template>
<div class="myClass"></div>
</template>
<title>Sprinkler System</title>
<p id="System" class="myClass"></p>
<p id="PumpPres" class="myClass"></p>
<p id="PumpCurrent" class="myClass"></p>
<h6><i>This is in develoupement build</i></h6>
<h3>Message<br>
<input type="text" id="InputRandom"></input> <input onclick="Random1()" type="button" value="Send Message" id="Input2"></input>
</h3>
<br>
<h4> Sprinkler System <br><input type="number" id="InputTxt" min="1" max="12"></input>
<input onclick="SS_On()" type="button" value="Turn On"></input>
<input onclick="SS_Off()" type="button" value="Turn Off" id="RandomBtn"></input>
</h4>
<p id="this" class="myClass"></p>
<input onclick="reset()" type="button" value="reset"></input>
<p id="mic"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
<script>
/*=============================================Variables================================================*/
var HomeLog = "home/irrigation/state";
var LogSS = "home/irrigation/log";
var SS_dest = "home/irrigation"; //SS == Sprinkler System
var SS_Pres = "home/irrigation/pressure";
var SS_Current = "home/irrigation/pump_current"
var Ip = "192.168.1.46"; //ip adress of the broker
var Port = Number(8083); //port of the broker
var Id = makeid(); //writes the ip
var mes; //makes mes global
var num = 0;
var Log;
/*==============================================MQTT====================================*/
client = new Paho.MQTT.Client(Ip, Port, Id);
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
onSuccess: onConnect
});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected as " + makeid());
client.subscribe(SS_dest);
client.subscribe(LogSS);
client.subscribe(HomeLog);
client.subscribe(SS_Pres);
client.subscribe(SS_Current);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
var TimeOut;
var Object1 = responseObject.errorCode;
if (Object1 !== 0) {
console.log("ConnectionLost:" + responseObject.errorMessage);
//client = new Paho.MQTT.Client(Ip, Port, Id);
client.connect({
onSuccess: onConnect
});
TimeOut++;
}
if (TimeOut == 10) {
Object1 = 1;
}
}
// called when a message arrives
function onMessageArrived(message) {
var OnOff;
console.log("MessageArrived:" + message.payloadString);
mes = message.payloadString;
//alert(mes);
var res = mes.split(","); //holds if statement
if (res[1] == "on" || res[1] == "On") {
OnOff = "On";
} else if (res[1] == "Off" || res[1] == "Off") {
OnOff = "Off";
}
var Test1 = res.length;
if (Test1 >= 2) {
//alert(Test1);
document.getElementById("p" + res[0]).innerHTML = "Zone " + res[0] + " == " + OnOff;
}
console.log("Topic: " + message.destinationName);
Log = message.destinationName;
console.log(Log);
if (Log == "home/irrigation/state") {
document.getElementById("System").innerHTML = "Pump == " + mes;
}
if (Log == "home/irrigation/pressure") {
document.getElementById('PumpPres').innerHTML = "Presure == " + mes;
}
if (Log == "home/irrigation/pump_current") {
document.getElementById('PumpCurrent').innerHTML = "Current == " + mes;
}
if (Log != "home/irrigation/pump_current" && Log != "home/irrigation/pressure") {
document.getElementById("mic").innerHTML = document.getElementById("mic").textContent + "," + mes;
document.getElementById("mic").style.fontSize = "small";
num = num + 1;
Loop1();
}
}
/*==========================================Functions=================================*/
makeBigger();
test();
function SS_On() { //turn on the system
var elem = document.getElementById("InputTxt") //gets the input of the textbox
if (elem.value < 13 && elem.value >= 1) { //detects if the input is in a certan range
message = new Paho.MQTT.Message(elem.value + ",On"); //wrights a message
message.destinationName = SS_dest; //sets the destonation of the message
client.send(message); //sends the message to the broker
}
}
function SS_Off() { //turn off the system
var elem = document.getElementById("InputTxt") //gets the input of the textbox
if (elem.value < 13 && elem.value >= 1) { //detects if the input is in a certan range
message = new Paho.MQTT.Message(elem.value + ",Off"); //wrights a message
message.destinationName = SS_dest; //sets the destonation of the message
client.send(message); //sends the message to the broker
}
}
function makeid() { //this is made to make a randomized id
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function Random1() { //made for a helloworld
var elem1 = document.getElementById("InputRandom");
message = new Paho.MQTT.Message(elem1.value); //wrights a message
message.destinationName = LogSS; //sets the destonation of the message
client.send(message); //sends the message to the broker
}
function Loop1() { //made to reset the log
if (num == 5) {
document.getElementById("mic").innerHTML = mes;
num = 0;
}
}
function reset() { //ment for the reset button
num = 0;
document.getElementById("mic").innerHTML = " ";
}
function test() { //this is made to make the p1-p12 in the HTML
for (nom = 1; nom <= 12; nom++) {
document.getElementById("this").innerHTML = document.getElementById("this").innerHTML + "<p id=p" + nom + " class=myClass>Zone " + nom + " == Off</p>";
}
}
function makeBigger() {
var txt = document.getElementById("InputTxt");
txt.style['width'] = '165px';
}
</script>
</body>
</html>
try to use a fixed font-size for your .myClass, hope helpful.

Property within an array not being read by a function - Cannot read property of undefined

I am having some trouble. I am working within Business Catalyst which stores dynamic user-submitted data and allows me to output it in whatever way I need.
I have created a series of Web Apps that work together to allow users to take quizzes. Currently I am receiving an error message 'Uncaught TypeError: Cannot read property 'questionText' of undefined'
How my code is working currently:
A user submits a form with quiz/survey data.
They are directed to a new page that runs a search for the most recent quiz/survey submission unique to their user.
The data is output on the page within a div.
A function reads the data and builds the page content accordingly to display the correct quiz/survey results.
The data that is submitted is output in the following format. Note that the {tags} are Business Catalysts way of outputting dynamic information - the {tag} is replaced with the user-submitted data on the page. Also note that I have only shown the data for 3 questions, there are up to 15 in total.
var quizSurvey = "{tag_quiz/survey}";
var w = window.innerWidth;
function Question(questionNumber, questionText, answerType, answerA, answerB, answerC, answerD, correctAnswer, userMultichoice, userTF, userSRating, userSSAnswer, qPassFail) {
this.questionNumber = questionNumber;
this.questionText = questionText;
this.answerType = answerType;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.answerD = answerD;
this.correctAnswer = correctAnswer;
this.userMultichoice = userMultichoice;
this.userTF = userTF;
this.userSRating = userSRating;
this.userSSAnswer = userSSAnswer;
this.qPassFail = qPassFail;
};
var question = new Array();
question[1] = new Question("1", "{tag_q1-question}", "{tag_q1-answer-type}", "{tag_q1-multichoice-a}", "{tag_q1-multichoice-b}", "{tag_q1-multichoice-c}", "{tag_q1-multichoice-d}", "{tag_q1-correct-answer}", "{tag_q-multichoice-1}", "{tag_q-t/f-1}", "{tag_s-ratings-1}", "{tag_s-shortanswer-1}", "{tag_q1-pass/fail}");
question[2] = new Question("2", "{tag_q2-question}", "{tag_q2-answer-type}", "{tag_q2-multichoice-a}", "{tag_q2-multichoice-b}", "{tag_q2-multichoice-c}", "{tag_q2-multichoice-d}", "{tag_q2-correct-answer}", "{tag_q-multichoice-2}", "{tag_q-t/f-2}", "{tag_s-ratings-2}", "{tag_s-shortanswer-2}", "{tag_q2-pass/fail}");
question[3] = new Question("3", "{tag_q3-question}", "{tag_q3-answer-type}", "{tag_q3-multichoice-a}", "{tag_q3-multichoice-b}", "{tag_q3-multichoice-c}", "{tag_q3-multichoice-d}", "{tag_q3-correct-answer}", "{tag_q-multichoice-3}", "{tag_q-t/f-3}", "{tag_s-ratings-3}", "{tag_s-shortanswer-3}", "{tag_q3-pass/fail}");
var userScore = "{tag_total score}";
var passingScore = "{tag_required score to pass}";
var showAnswers = "{tag_show answers}";
So now that you see how the Data is stored, here is the code for the page that it is output on. Note that I left out Step 2, the code that runs the search - I know this works, so I didn't think you would need to see it.
<div class="row">
<div class="small-12 columns">
<div class="quiz-survey-search" id="qs-results" style="display: block;"> {module_webappscustomer,19627,l,,,_self,true,1,true,1} </div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<div class="correct" id="correct" style="display: none;">
<h2 id="quiz-headline-1" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">Good work completing this chapter!<br />
Your score is:</h4>
<div class="large-score" id="score-1"></div>
</div>
<div class="incorrect" id="incorrect" style="display: none;">
<h2 id="quiz-headline-2" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">You did not achieve the required passing score. Please review the materials and take the quiz again to complete this chapter.</h4>
<div class="large-score" id="score-2" style="margin:3rem 0rem;"></div>
</div>
<div class="survey" id="survey" style="display: none;">
<h2>Thank you for completing the survey.</h2>
<h4>Your answers have been submitted.</h4></div>
</div>
<div id="correct-answers" style="display: none;">
<h3 style="text-decoration: underline;">Correct Answers</h3>
<p style="font-weight: bold;">Although you passed the quiz you had one or more answers that were incorrect.
Below are the correct answers.</p>
<div class="row">
<div id="incorrectQuestions"></div>
</div>
</div>
</div>
<script>
var quizsurveyDiv = document.getElementById('qs-results').innerHTML;
if (quizsurveyDiv == " ") {
var element = '{module_url,AllIDs}';
var arrayOfStrings = element.split("-");
document.getElementById('CAT_Custom_206').value = arrayOfStrings[0];
document.getElementById('CAT_Custom_2').value = arrayOfStrings[1];
document.getElementById('CAT_Custom_3').value = arrayOfStrings[2];
catcustomcontentform9225.submit();
} else {
if (quizSurvey == "Quiz") {
var qNumber = 0;
var qNumbers = function() {
for (i = 0; i <= 14; i++) {
if (question[i].questionText !== "") {
qNumber = qNumber + 1;
console.log('here - ' + qNumber);
};
};
};
var writeDivs = function() {
var incorrectQDiv = "";
for (i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
incorrectQDiv = document.getElementById('incorrectQuestions').innerHTML;
document.getElementById('incorrectQuestions').innerHTML = incorrectQDiv + "<div class='small-12 medium-6 columns incorrectQ' id='incorrectQ-" + question[i].questionNumber + "'>Hi!!</div>";
console.log('here2 - ' + qNumber);
} else if (question[i].qPassFail == "1") {
};
};
};
var writeQContent = function() {
for (var i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
if (question[i].answerType == "True/False") {
var qUserAnswer = question[i].userTF;
} else {
qUserAnswer = question[i].userMultichoice;
};
document.getElementById('incorrectQ-' + question[i].questionNumber).innerHTML = "<p><span class='pinkNum'>" + question[i].questionNumber + "</span>" + question[i].questionText + '</p><div class="row"><div class="small-12 small-push-12 medium-6 columns"><p><span class="pink-title">Your Answer: ' + qUserAnswer + '</span><br/><div id="incorrectA-' + question[i].questionNumber + '"></div></p></div><div class="small-12 small-pull-12 medium-6 columns"><p><span class="pink-title">Correct Answer: ' + question[i].correctAnswer + '</span><div id="correctA-' + question[i].questionNumber + '"></div></p></div></div>';
};
if (question[i].qPassFail == "0" && question[i].answerType == "Multiple Choice") {
var correctADiv = "correctA-" + question[i].questionNumber; console.log(correctADiv);
if (question[i].correctAnswer == "A") {
document.getElementById(correctADiv).innerHTML = question[i].answerA;
} else if (question[i].correctAnswer == "B") {
document.getElementById(correctADiv).innerHTML = question[i].answerB;
} else if (question[i].correctAnswer == "C") {
document.getElementById(correctADiv).innerHTML = question[i].answerC;
} else {
document.getElementById(correctADiv).innerHTML = question[i].answerD;
};
};
};
};
var showTheAnswers = function() {
if (quizPassFail == "1") {
document.getElementById('quiz-headline-1').innerHTML = "You passed the quiz: " + quizName;
document.getElementById('score-1').innerHTML = '<span class="large-score">' + totalScore + '%</span>';
document.getElementById('correct').style.display = "block";
if (showAnswers == "1") {
if (totalScore != "100") {
document.getElementById('correct-answers').style.display = "block";
} else if (showAnswers != "1" || totalScore == "100") {
document.getElementById('correct-answers').style.display = "none";
};
};
} else {
document.getElementById('quiz-headline-2').innerHTML = "Unfortunately you did not pass the quiz: " + quizName ;
document.getElementById('score-2').innerHTML = '<div class="hide-for-small medium-1 large-2 columns"> </div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="userScore"></span><br/>Your Score</p></div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="requiredScore"></span><br />Required Score</p></div><div class="hide-for-small medium-1 large-2 columns"> </div>';
innerScores();
document.getElementById('incorrect').style.display = "block";
};
};
var innerScores = function() {
document.getElementById('userScore').innerHTML = totalScore + "%";
document.getElementById('requiredScore').innerHTML = requiredScore + "%";
console.log('innerScores');
};
if (showAnswers == "1" && totalScore != "100") {
qNumbers();
writeDivs();
writeQContent();
showTheAnswers();
} else if (showAnswers == "0" && totalScore != "100") {
showTheAnswers();
} else {
showTheAnswers();
}
} else if (quizSurvey == "Survey") {
document.getElementById('survey').style.display = "block";
};
courseCompletePass();
};
Thank you for any and all possible help. This has been an extremely difficult coding process and any help would be greatly appreciated!

Categories