Trouble concatenating strings - javascript

I'm having an issue concatenating strings. Where I initially declare the 'output' variable in my last function, I'm able to get the number of questions correct printed to my modal window.
However, my concatenation of strings 2 lines down from that won't work and I've tried so many things. I'm sure it's something simple but any help would be appreciated!
I'm not sure how much code is relevant to the solution so I apologize for the wall of code.
I'm new to JS and my first post on Stackoverflow so any tips or advice is appreciated. Thanks in advance!
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = document.getElementById("quizResults").innerHTML = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script

(Disclaimer: This answer might not actually solve your problem, as noted in the comments. I can't delete it, though, because it was accepted.)
(Please see the other answer)
The line
var output = document.getElementById("quizResults").innerHTML = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
does not have the effect you think it does, because javascript does not interpret a statement like var a = b = c the way you think it does. Instead, it is better to use var a = c; var b = c;, like so:
var output = 'You got '+answersRight+ ' out of ' +questionNumber+ ' answers correct!';
document.getElementById("quizResults").innerHTML = output;
For more information on how javascript interprets var a = b = c;, please see this question: Javascript a=b=c statements

The problem is that you're updating the output variable after you've already put it into the quizResults DIV. Assigning the string to .innerHTML makes a copy of it, it's not a reference to the variable, so updating the variable doesn't change the DIV contents. You need to assign to .innerHTML after you've performed the concatenation.
var randomNum1 = 0;
var randomNum2 = 0;
var correctAnswer = 0;
var questionNumber = 0;
var question = "<h2>Question #: " + questionNumber + "</h2>";
var answersRight = 0;
//jQuery command to make enter key submit answer
$(document).keypress(function(e) {
if (e.which == 13) {
$("#sub").click();
}
});
//questions object
var questionsAsked = [
];
generateRandom();
document.getElementById('finished').style.display = 'none';
//check answer, push question info to array
function check() {
var userAnswer = parseInt(document.getElementById("userAnswer").value);
document.getElementById('userAnswer').value = "";
if (userAnswer === correctAnswer) {
answersRight++
} else {
answersRight += 0;
}
if (questionNumber < 3) {
next();
} else {
document.getElementById('sub').style.display = 'none';
document.getElementById('submitForm').style.display = 'none';
document.getElementById('finished').style.display = 'block';
finish();
}
}
function random() {
return Math.floor(Math.random() * 50) + 1;
}
//generate random numbers
function generateRandom() {
randomNum1 = random();
randomNum2 = random();
document.getElementById("randomNum1").innerHTML = randomNum1;
document.getElementById("randomNum2").innerHTML = randomNum2;
correctAnswer = randomNum1 + randomNum2;
questionNumber += 1;
question = "<h2>Question #: " + questionNumber + "</h2>";
$("#question").html(question);
questionsAsked.push([questionNumber, randomNum1, randomNum2, correctAnswer]);
}
//next button
function next() {
generateRandom();
}
function finish() {
var output = 'You got ' + answersRight + ' out of ' + questionNumber + ' answers correct!';
var percent = Math.round((answersRight / questionNumber) * 100);
output += ' You got ' + percent + '% on this quiz! Outstanding!';
document.getElementById("quizResults").innerHTML = output;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<div>
<h1 class="text-center">Welcome to Math World!</h1>
</div>
<div>
<div id="question">
</div>
<div id="questionArea">
<br>
<h3>Add the following numbers</h3>
<h3 id="randomNum1"></h3>
<h3>+</h3>
<h3 id="randomNum2"></h3>
<p id="message"></p>
</div>
<div id="submitForm">
<div class="form-inline">
<div class="form-group">
<label for="answer">Enter Answer:</label>
<input type="text" class="form-control" id="userAnswer" placeholder="Type answer here">
</div>
<button id="sub" type="submit" class="btn btn-primary" onclick="check()">Submit Answer</button>
</div>
</div>
<button id="finished" type="submit" class="btn btn-success" data-toggle="modal" data-target="#myModal">Finish Quiz</button>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Quiz Results</h4>
</div>
<div id="quizResults" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script

Related

Merging two variables in one and equaling it with another one

The code doesn’t have any error, but doesn’t work. I fill both inputs and click the button but it doesn’t print out the words.
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = listItem.textContent;
let myTodoTime = timeInputValue.textContent;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime;
myTodoInfo = getInputValue.value;
}
<div class="myApp border border-info">
<p class="text-center appTittle">To Do List</p>
<div class="todoThings" id="todo">
<ul>
<li id="todoListItem"></li>
</ul>
</div>
<div class="row mx-auto">
<p class="mr-3 ml-3 appTaskText">Task</p><input type="text" class="appInput" id="task">
<p class="mr-1 ml-3 appTaskText">Time</p><input type="number" id="timeInput" min="1" max="24">
</div>
<button type="submit" class="btn btn-info btn-sm addButton" id="add" onclick="addTask()">Add task</button>
<p id="errorMsg" class="text-danger mt-1 mb-1"></p>
</div>
This is not the full solution, However, i have corrected the variables to fix the basic issue of not showing the task. You should get some help with this solution and extend it.
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = getInputValue.value;
let myTodoTime = timeInputValue.value;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime;
myTodoInfo = getInputValue.value;
listItem.innerHTML = myTodoInfo;
}
<div class="myApp border border-info">
<p class="text-center appTittle">To Do List</p>
<div class="todoThings" id="todo">
<ul>
<li id="todoListItem"></li>
</ul>
</div>
<div class="row mx-auto">
<p class="mr-3 ml-3 appTaskText">Task</p><input type="text" class="appInput" id="task">
<p class="mr-1 ml-3 appTaskText">Time</p><input type="number" id="timeInput" min="1" max="24">
</div>
<button type="submit" class="btn btn-info btn-sm addButton" id="add" onclick="addTask()">Add task</button>
<p id="errorMsg" class="text-danger mt-1 mb-1"></p>
</div>
I fixed my issue this is the fix
let listItem = document.getElementById('todoListItem');
let timeInputValue = document.getElementById('timeInput');
let getInputValue = document.getElementById('task');
let errorMessageInput = document.getElementById('errorMsg');
function addTask() {
if (getInputValue.value.trim() === "") {
errorMessageInput.textContent = "You haven't added a todo item, please add it in order to show up";
return;
}
let myTodoInput = getInputValue.value;
let myTodoTime = timeInputValue.value;
let myTodoInfo = myTodoInput + ' at ' + myTodoTime + 'PM';
listItem.textContent = myTodoInfo;
}
let myTodoInput = listItem.textContent;
let myTodoTime = timeInputValue.textContent;
let myTodoInfo = myTodoInput + ' Time ' + myTodoTime; // line isn't of value as it is overwritten below
myTodoInfo = getInputValue.value; // overwrites declaration.`
You are not printing anyway. No console.log() or alert() and no DOM injection.

Javascript variable doesn't add values as it should

I have this code in html and javascript
HTML
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "You answered " + correct_ans + " correctly.";
if (answer_one === "abuja") {
correct_ans++;
}
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
my issue is that the correct_ans variable doesn't add when i type in the correct answer in the textbox
You should initialize the variable result after you check for the correct answer.
function getResult() {
let correct_ans = 0;
let answer_one = document.getElementById("question_one").value;
if (answer_one === "abuja") correct_ans++;
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->
In your code, result was evaluated before the correct_ans increment.
Try this instead.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
let result = "";
if (answer_one === "abuja") {
correct_ans++;
}
result = You answered " + correct_ans + " correctly.
document.getElementById("result").innerHTML = result;
}
You declared the variable abuja before you updated the variable correct_ans. Put it after the if condition. If you'll add other questions you need to put the initial declaration of correct_ans = 0 out of the function or you're always going to get 0 or 1.
function getResult() {
let answer_one = document.getElementById("question_one").value;
let correct_ans = 0;
if (answer_one === "abuja") {
correct_ans++;
}
let result = "You answered " + correct_ans + " correctly.";
document.getElementById("result").innerHTML = result;
}
<div class="container">
<div class="question1">
<p>What is the capital of Nigeria</p><br>
<input type="text" id="question_one">
</div>
<button id="button" onclick="getResult();">Submit</button>
</div>
<!--end of container-->
<div class="button_after">
<h1 id="result"></h1>
</div>
<!--end of button_after-->

Getting undesired result in node/angularjs application

I am making a MEAN stack application. It is an online live test taking application where user has to face a multiple choice question with 4 options and has to choose one.
Now, the problem i'm getting is, suppose there are 2 questions:
1. What is 1+0?
a. 1
b. 3
c. 4
d. 5
The answer to this question is at index 1,also the answer is 1. So my controller is sending 1 to the Submit button(it's sending the index, not the actual answer).
Take another question. What is 3+4?
a. 7
b. 8
c. 9
d. 10
Here, the controller sends 1 to the database, as the correct answer marked by user is at first index.
I want it to send 7.
This is my controller
liveController.js
examApp.controller('liveController', ['$scope', '$filter', '$http', '$location', '$routeParams', 'queryService', 'authenticationService', function($scope, $filter, $http, $location, $routeParams, queryService, authenticationService) {
var main = this;
var totalnoofQuestions;
var user;
main.questionsforTime = [];
this.getsecurityQuestion = function() {
var data = {
_id: $routeParams.userId
}
queryService.getsecurityQuest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
var userId;
var data = response.data.data;
main.user = data.name;
main.userId = data._id;
authenticationService.setToken(response.data.token);
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getsecurityQuestion();
this.logged = function() {
main.username = queryService.userName;
if (queryService.log == 1 || queryService.userId !== 'undefined') {
return 1;
} else {
$location.path('/');
}
}
this.logged();
this.userId = $routeParams.userId;
main.heading = "Welcome To Exam App";
$('.thisismodalforlivetestwarning').modal('show');
$(document).on('click', '#returntotaketest', function() {
$('.thisismodalforlivetestwarning').modal('hide');
location.replace("#/taketheTest/" + main.userId);
})
this.getasingleTest = function() {
var singletestId = $routeParams.testId;
queryService.getasingleTest(singletestId)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
window.location.href = "#/taketheTest/" + main.userId;
} else {
if (response.data.data.questions.length == 0) {
$location.path("/taketheTest/" + main.userId);
alert("No questions present.");
} else {
main.totalnoofQuestions = response.data.data.questions.length;
main.questionsforTime.push(response.data.data.questions.length);
main.testHeading = "Test topic is " + response.data.data.testName;
main.singletestArray = response.data.data.questions;
main.time = response.data.data.testDuration;
}
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getasingleTest();
var totalSeconds = 300;
var minutes = parseInt(totalSeconds / 60);
var seconds = parseInt(totalSeconds % 60);
this.theTime = function() {
totalSeconds = totalSeconds - 1;
minutes = parseInt(totalSeconds / 60);
seconds = parseInt(totalSeconds % 60);
main.timetakeninTest = (300 - totalSeconds);
document.getElementById('test-time-left').innerHTML = 'Time Left: ' + minutes + ' minutes ' + seconds + ' seconds';
if (totalSeconds <= 0) {
clearTimeout(main.counttime);
main.timetakeninTest = 300;
alert("Time Is Up!!");
container.style.display = 'none';
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
}
var currentQuestion = 0;
var score = 0;
var totalQuestionAsked = 0;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
this.loadQuestion = function(questionIndex) {
if (questionIndex == 0) {
totalQuestionAsked = main.totalnoofQuestions;
$('.thisismodalforlivetestwarning').modal('hide');
main.counttime = setInterval(this.theTime, 1000);
}
var q = main.singletestArray[questionIndex];
questionEl.textContent = (questionIndex + 1) + '.' + q.question;
opt1.textContent = q.optionA;
opt2.textContent = q.optionB;
opt3.textContent = q.optionC;
opt4.textContent = q.optionD;
};
this.nextQuestion = function() {
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
var answer = selectedOption.value; //This line
console.log("this is problem " + answer);
if (main.singletestArray[currentQuestion].answer == answer) {
score += 10;
}
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
questionid: main.singletestArray[currentQuestion]._id,
userAnswer: answer,
correctAnswer: main.singletestArray[currentQuestion].answer,
timetakenInsecs: main.timetakeninTest
}
queryService.submitAnswer(data)
.then(function successCallback(response) {}, function errorCallback(response) {})
selectedOption.checked = false;
currentQuestion++;
if (currentQuestion == totalQuestionAsked - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totalQuestionAsked) {
container.style.display = 'none';
clearTimeout(main.counttime);
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem");
})
return;
}
this.loadQuestion(currentQuestion);
}
}]);
<link rel="stylesheet" href="../css/livetest.css">
<!-- W3 schools styles-->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
<div ng-controller="liveController as live">
<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse">
<br/>
<div class="container">
<a class="navbar-brand" href="">
<h2>
<i class="fa fa-line-chart" aria-hidden="true"></i> Exam App Dashboard
</a>
</div>
<br/>
</nav>
<div Style="color:white;font-weight:bold;font-size:2em; text-align:center;" id="test-time-left"></div>
<div style="background: #F2F2F2;" id="quizContainer" class="container">
<div class="title" style="text-align: center; font-weight:bold; font-size: 1.5em;">{{live.testheading}}</div>
<div id="question" class="question" style="font-size: 2em; font-weight: bold;"></div>
<label class="option">
<input type="radio" name="option" value="1" />
<span id="opt1"></span>
</label>
<label class="option">
<input type="radio" name="option" value="2" />
<span id="opt2"></span>
</label>
<label class="option">
<input type="radio" name="option" value="3" />
<span id="opt3"></span>
</label>
<label class="option">
<input type="radio" name="option" value="4" />
<span id="opt4"></span>
</label>
<button id="nextButton" class="next-btn" ng-click="live.nextQuestion()">Next Question </button>
</div>
<br/>
<!-- Place to keep all the modals -->
<!-- Modal -->
<div class="modal fade thisismodalforlivetestwarning" id="modalfortestwarning" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Please Read The instructions Carefully :</span>
</h4>
</div>
<div class="modal-body">
<ol>
<li>You will be alloted 5 Minutes to Give Test, After which window will close Automatically.</li>
<li>You can't go back after submitting the Answer for each Question.</li>
<li>you can submit the Test before the finishing Time if you want but can't after the time finishes, It will Automatically be submitted.</li>
<li>Please don't do cheating in test. Be fair to yourself for your true Assessment of skills.</li>
<li>If you aggree with all the terms stated above you may proceed by clicking Start Button Below.</li>
</ol>
<h3 align="center">
<strong>
<em>Best Of Luck!</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-success" ng-click="live.loadQuestion(0)">Start!</button>
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
<!-- MOdal for User Performance -->
<!-- Modal -->
<div class="modal fade thisismodalforUserTestPerformance" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Your Score Card for the Test :</span>
</h4>
</div>
<div class="modal-body">
<div style="background-color: #404549;" class="modal-body">
<a class=" list-group-item">User ID: {{live.performanceUserID}}</a>
<a class=" list-group-item">Total Correct Answers: {{live.answerscorrect}}</a>
<a class=" list-group-item">Total Wrong Answers: {{live.answerswrong}}</a>
<a class=" list-group-item">Score Secured: {{live.madeScore}}</a>
<a class=" list-group-item">Total Time Taken: {{live.timeTaken}} Seconds</a>
</div>
<h3 align="center">
<strong>
<em>Thank You! For giving the Test...</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
The action happens at nextQuestion function at the commented line (commented with '//This line'). I have tried my best to explain my problem and can upload more code if required.
Any help will be appreciated.
You could do something like this
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
//As selectedOption is actually an index we can use it to get the answer
var answerValue = document.getElementById('opt'+ selectedOption);
var answer = answerValue.textContent;

Javascript based game

So i've been trying make a game where you bet money and if you win you get a profit, to win you must guess the correct outcome of the dice (6 sided) if you do you get your money + profit, i have been kind of successful but it dosen't pay you.
if you could help me fix this thanks. WEBSITE: http://csgodice.net16.net/dice.php
EDIT : Added the whole code!
EDIT: Things still broken with a new error: game is not defined.
CSGODice.net
<div id="header">
<div id="navbar">
<a class="nav1" href="/"><bold>HOME</bold></a>
<a class="nav2" href="dice.php"><bold>DICE</bold></a>
<a class="nav3" href="support.php">SUPPORT</a>
<a class="balance" href="#">Gems: 0</a>
<div id="steamLogon">
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
loginbutton("small"); //login button
} else {
include ('steamauth/userInfo.php'); //To access the $steamprofile array
//Protected content
logoutbutton(); //Logout Button
}
?>
</div>
</div>
<div id="dicelogo">
<a href="/">
<img src="img/logo.png" alt="logo" id="logo"/>
</a>
</div>
</div>
<div id="dicegame">
<div id="diceholder">
<h1>
<div id="diceroller">
<span id="value" class="lable_value">0</span>
<script>
var m = document.getElementsByClassName("balance");
var o = document.getElementsById("diceroller");
var w = document.getElementsByClassName("winchance");
var uc = document.getElementsByClassName("userchoice").value;
var b = document.getElementsById("bet").value;
var p = document.getElementsById("profit");
function game(event){
var wn = Math.floor((Math.random() * 6) + 1);
o.innerText = wn;
if(uc.value == wn) {
m.innerText = m.innerText + profit.innerText + b;
} else {
m.innerText = m.innerText - b;
}
}
</script>
</div>
</h1>
<h3>
<div class="winchance">1 - 6</div>
</h3>
</div>
<div id="inputholder">
<div id="input">
<div class="betamount">
<b>Gems to bet:</b>
</div>
<form class="input-money">
<b><input id="bet" oninput="edValueKeyPress()" type="number" name="bet" style="color: #404040;" class="form-control" min="0.10" step="any" max="1000.00" value="1.00"></b>
</form>
<div class="profitamount">
<b>Profit:</b>
</div>
<div id="profit">
</div>
<div id="userchoicetext"><b>Prediction:</b></div>
<form>
<input id="userchoice" oninput="edValueKeyPress()" type="number" name="choice" style="color: #404040" class="form-choice" min="1" step="any" max="6" value="1"/>
</form>
<button id="playgame" onclick="game()">Throw!</button>
</div>
</div>
</div>
<script>
var input = document.getElementsByClassName("form-control");
function edValueKeyPress(event)
{
var input = document.getElementById("bet").value;
var x = document.getElementById("profit"); // Find the elements
x.innerText= input * 0.68; // Change the content
var n = event.toFixed(2);
}
</script>
</div>
</div>
</div>
You have several errors here:
First a simple typo:
You define a variable here
var b = document.getElementsById("bet").value;
an try to access it as bet
m.innerText = m.innerText + profit.innerText + bet;
Next misstake:
getElementsById must be getElementById
next:
getElementsByClassName returns an array of Nodes, not only the first node it finds, so var uc = document.getElementsByClassName("userchoice").value; is an error.
Your debugged code:
var m = document.getElementsByClassName("balance")[0];
var o = document.getElementById("diceroller");
var w = document.getElementsByClassName("winchance")[0];
var uc = document.getElementsByClassName("userchoice")[0].value;
var bet = document.getElementById("bet").value;
var p = document.getElementById("profit");
function game(event){
var wn = Math.floor((Math.random() * 6) + 1);
o.innerText = wn;
if(uc.value == wn) {
m.innerText = m.innerText + profit.innerText + bet;
} else {
m.innerText = m.innerText - b;
}
}
I'd highly recommend to give those specific elements an ID and find them via that, rather than a classname.
All these errors are shown in the console - one after each other. Use that to debug your code yourself in the future!

Cannot call the second javascript function (differently named) on the same page

I'm trying to implement an extend form function in two places on the same page. The first place works fine, but the second place does not even call the function apparently.
The html and js of the first place:
<span id="readroot" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<div class="row">
<!-- Content not displayed for simplicity purpose -->
</div>
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields()" value="Give me more fields!" />
<script>
var counter = 1;
function moreFields() {
counter++;
var newField = document.getElementById('readroot').cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[Student][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
//console.log(newFields[i].htmlFor);
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newField,insertHere);
}
</script>
The second:
<span id="readroot2" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<div class="row">
<!-- Content not displayed for simplicity purpose -->
</div>
</span>
<span id="writeroot2"></span>
<input class="btn btn-default" type="button" onChange="moreFields2()" value="Give me more fields!" />
<script>
var counter = 1;
function moreFields2() {
counter++;
var newField = document.getElementById('readroot2').cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[Condition][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById('writeroot2');
insertHere.parentNode.insertBefore(newField,insertHere);
}
</script>
I have tried by naming all the variables in the second function differently. But it seems irrelevant..
First you have use two different events on both input
<input class="btn btn-default" type="button" onclick="moreFields()"
<input class="btn btn-default" type="button" onChange="moreFields2()"
So make sure that you are looking for same functionality on both than they will not..
onChange will fire after element change not while you type here check for code so be clear what you wanted. Because onChange will fire on blur in this case
The second function is not firing on onChange event. If you try to design the function accordingly you could have to reduce the effort to writing too many java script.
<span id="readroot" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<div class="row">
<!-- Content not displayed for simplicity purpose -->
</div>
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot','writeroot')" value="Give me more fields!" />
<span id="readroot2" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<div class="row">
<!-- Content not displayed for simplicity purpose -->
</div>
</span>
<span id="writeroot2"></span>
<input class="btn btn-default" type="button" onClick="moreFields('readroot2','writeroot2')" value="Give me more fields!" />
<script>
var counter = 1;
function moreFields(node, insertNode) {
counter++;
var newField = document.getElementById(node).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i = 0; i < newFields.length; i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[Condition][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(insertNode);
insertHere.parentNode.insertBefore(newField, insertHere);
}
</script>
Please counter check it again for the functionality. And you may please optimize the code.

Categories