Javascript variable doesn't add values as it should - javascript

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-->

Related

Why is this simple username sys not working?

I want to create a chat system (which i already accomplished), but a working username selector, and it gets the username in the input, then when the user sends a message via chat, it is their username!! And also, i tried putting it in a localStorage, so when the user refreshes or rejoins, the name is still there and not removed! I think im close, but it says UNDEFINED, which really got me confused? Please help? Thanks!!
localStorage.playerusername = document.querySelector(".hud-name").value;
let username = localStorage.playerusername;
let chatMsg = [];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" + currentUserName + ": </strong>" + chatMessage;
document.querySelector(".chat").appendChild(chatElem);
}
for (let i = 0; i < chatMsg.length; i++) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
sendMessage: function(messageContent) {
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
document.querySelector(".enterT").innerHTML = ""
},
addChatTopRemoverPackage: async function() {
if (chatMsg.length == 7) {
let chatElem = document.querySelector(".chat")
if (chatElem.children[0]) {
chatElem.removeChild(chatElem.children[0])
if (chatMsg.length > 0) {
chatMsg.shift()
//if (chatMsg.length == 0) {
//chatMsg.pop();
//}
}
}
}
},
chatRemoverRefresher: setInterval(() => {
Game.currentGame.variables.addChatTopRemoverPackage()
}, 0.000000000001)
}
}
}
HTML:
<div class="hud-name-select
type-text
maxlength-16
">
<input class="hud-name" type="text" maxlength="16" placeholder="Enter Nickname...">
<div></div>
<div><br></div>
<button class="btn-play btn-green background-color-green">
<div style="
display: none;
" display="none">Loading......<div></div>
</div>
<span>Play</span>
</button>
</div>
</div>
</div>
<div class="msgcont">
<div class="messages">
<h1>
CHAT
</h1>
<div class="chat">
</div>
<div>
<input class="enterT" type="text" placeholder="Enter A Message..!"><button
onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
</div>
<br>
</div>
</div>
Kevin

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.

Why javascript not run line by line

Below are html/javascript code, but when call function calc(), its output a <ol>
tag first, but bot run script orderly.
I have remove the settimeout() function to make it running sync.
Can some one give explain will be appreciated.
function $(id) {
return document.getElementById(id);
}
regex_field = $('regx');
content = $('content');
output = $('output');
flag_field = $('flag')
flag_field.addEventListener('input', function() {
calc();
});
content.addEventListener('input', function() {
calc();
});
regex_field.addEventListener('input', function() {
calc();
});
function calc() {
//setTimeout(function () {
var re = new RegExp(regex_field.value, flag_field.value)
console.log(re);
found = content.value.match(re);
if (found) {
$('output').innerHTML = "<ol>";
for (let i = 0; i < found.length; i++) {
$('output').innerHTML += '<li>' + found[i] + '</li>';
}
$('output').innerHTML += "</ol>";
} else {
$('output').innerHTML = "Nothing Found!";
}
// }, 500);
}
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="col-sm-6 form-inline">
RegExp
<input class="col-sm-4 form-control form-control-sm" type="text" id="regx" placeholder="Regex Input"> Flag
<input class="col-sm-1 form-control form-control-sm" type="text" id="flag">
<br>
<div>
<p>Input Content</p>
<textarea class="form-control col-sm-12" name="input" placeholder="Text" id="content" cols="30" rows="10"></textarea>
</div>
</div>
<div class="col-sm-6">
<p>Content get</p>
<div id="output"></div>
</div>
</div>
</body>
</html>
Output is like below. I don't understand why 'ol' tage go above the 'li' tag.
<div id="output">
<ol></ol> // <--- question here
<li>12</li>
<li>34</li>
</div>
When you do $('output').innerHTML = "<ol>"; it immediately adds the ol tag to #output. Since an <ol> without a closing </ol> is invalid, the DOM automatically closes it. So you get:
<div id="output">
<ol></ol>
</div>
Then, you do $('output').innerHTML += '<li>' + found[i] + '</li>';, so it adds that line to #output (which is also invalid, since an li can't belong to a div, but it doesn't know how to fix it):
<div id="output">
<ol></ol>
<li>12</li>
</div>
What you want to do it build up the innerHTML, then set it all at once, so more like:
if (found) {
var output = '';
output = "<ol>";
for (let i = 0; i < found.length; i++) {
output += '<li>' + found[i] + '</li>';
}
output += "</ol>";
} else {
output = "Nothing Found!";
}
$('output').innerHTML = output;

Trouble concatenating strings

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

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!

Categories