cannot get a variable to pass from function called onclick - javascript

I am calling a function onclick secVar(sec1); which should run it through the script below, but it does not seem to be doing so, can someone tell me what I am doing incorrectly. I am new to javascript, and only have a little experience into scripting, and this code seems to be doing less and less of what I want it to.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function secVar(){
if(sec1) {
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
if(sec2) {
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
if(sec3) {
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}
}
function largestVar(){
if (sec1 >= sec2 && sec1 >= sec3) {
//a
document.getElementById('rig').innerHTML = 'Test1';
} else if (sec2 >= sec1 && sec2 >= sec3) {
//b
document.getElementById('rig').innerHTML = 'Test2';
} else {
//c
document.getElementById('rig').innerHTML = 'Test3';
}
}
</script>
If this helps, The old code was the code below, before I tried to add in the script to determine the largest of the variables. It was incrementing the variables onclick, but no longer so. The onclick contained sec1Var() at that point.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function sec1Var(){
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
function sec2Var(){
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
function sec3Var(){
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}</script>
If someone can explain to me what I am doing wrong I would greatly appreciate it.

I think it's hard to tell what your intention is. Sparticus has it right IF what you're trying to do is see if sec1, 2, and 3 are currently true or false (0 or 1). Since they are currently false, the code will never do anything as Sparticus correctly points out.
However, I'm not convinced that's actually what you MEAN to do. It looks like the condition you want to check is whether or not you're trying to increment sec1, 2, or 3. In other words, "If you are passing me sec1, increment it and update a piece of HTML".
But variables don't work that way. When you say secVar(sec1) what you are actually saying is `secVar(0)'. I don't think that's your intention.
So, a big waste of my time if I'm wrong, but because I'm already rolling along, let's pretend I'm right:
secVar needs to be able to accept a parameter, but right now you've declared it void. Changing it to accept a parameter is a first step:
function secVar(param) { ... };
But this still won't do anything. Because when you're still passing it "0" with your existing syntax. You need to pass it something that can be checked, like a string:
secVar('sec1');
When you do this, you can now update your conditions to check which string is being passed
if (param === 'sec1') { ... }
Here's a fiddle: http://jsfiddle.net/ch4yk/
Notes:
The fiddle includes jQuery just for easy brute-force event binding on the buttons. It's just an example. You don't need jQuery; bind your events however you want.
It is currently not doing anything with the largest value function, even though the code is in the fiddle

None of your counters will increment in this implementation.
When secVar() gets run, all the counters are at zero. They never increment because they start at zero.

Related

Multiple of document.getElementById("elementId").innerHTML = () causing second one to return as null

First, let me explain what I'm trying to do: I want to make a script for a video game that counts how much money is in the game, and create an element to display it. The tracking the money part was easy, but apparently making elements is like the most confusing thing i've tried to do yet.
Lightshot screenshot of chrome console: https://prnt.sc/shszc2
The blue-highlighted line in the screenshot gave an error after being executed twice. I boxed the error message in red.
I'll take some code out of the script I have, mainly aiming for code that is important for the issue i want help with, leaving out code that I understand.
Also note that I am extremely new to generating graphics in Javascript, so if my ways of making elements are horrendous, then it's because I just kept trying random crap until something seemed to work and stuck with whatever that was.
// The elements that I created. Again i know next to nothing about elements, so the only thing that I
// know will work is this catastrophe.
var initialDiv = document.getElementById('onecup');
mainText = initialDiv.appendChild(document.createElement('mainText'));
mainText.style.position = 'absolute';
mainText.style.left="50%";
mainText.style.top="64px"
mainText.style.width = "290px";
mainText.style.height = "160px";
mainText.style.color = "white";
mainText.style.zindex = 1;
mainText.style.fontSize = "18px"
trackerBack = mainText.appendChild(document.createElement('trackerBack'));
trackerBack.style.position = 'absolute';
trackerBack.style.left="-200px"
trackerBack.style.top="0px"
trackerBack.style.width = "400px";
trackerBack.style.height = "160px";
trackerBack.style.backgroundColor = "black";
trackerBack.style.opacity = ".20"
trackerBack.style.zindex=1;
diffTotal = trackerBack.appendChild(document.createElement('diffTotal'));
diffTotal.id = "diffTotal"
diffTotal.style.position = 'absolute';
diffTotal.style.top="20%"
diffTotal.style.left="40%";
diffTotal.style.color = "rgba(255,255,255,255)";
diffTotal.style.opacity = "1"
diffTotal.style.zindex = 2;
diffTotal.style.fontSize = "30px"
diffFielded = diffTotal.appendChild(document.createElement('diffFielded'));
diffFielded.id = "diffFielded"
diffFielded.style.position = 'absolute';
diffFielded.style.top="-15px"
diffFielded.style.left="0px";
diffFielded.style.color = "rgba(255,255,255,255)";
diffFielded.style.opacity = "1"
diffFielded.style.zindex = 2;
diffFielded.style.fontSize = "20px"
// This function is used by a latter function to set the values of the text elements. I initially didn't
// have this but thought adding it would help, but nothing changed.
// By the way, "toBna2" stands for to "big number abbreviation". It doesn't do anything major, besides
// shrink down numbers. Tried removing it, problem still persists.
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
// This looping function controls the values that the elements display. However, I removed the code that
// tells the function what values to make the elements, so if you want to test it, I guess just define
// the 4 values as anything or make your own.
findValueDiff = setInterval(function() {
// If i make one of these lines a comment, it works, regardless of which one it is. But if i let both of
// them run, the second document.getElementById("elementId") returns as null. Always the second one.
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
conductValues("diffFielded", (aValU - bValU))
}
I even tried doing this:
conductValues = function(targetName, targetAssignment) {
if (document.getElementById(targetName) != "undefined") {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
}
But all that does is make the function fail on the first attempt, because always the second document.getElementById("elementId") returns as null.
I'm not entirely sure if I included enough information, but I don't know what else to add so hopefully I did. But if you need more information, just ask and i'll try to edit this post as swiftly as possible.
Thanks to all responders, and I hope you stay healthy as you have fun coding.
Edit 1: Thought i would get something different if I set the entity's variables one at a time like this:
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
loopMode=0
findValueDiff = setInterval(function() {
if (loopMode == 0) {
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
loopMode = 1
} else {
conductValues("diffFielded", (aValU - bValU))
loopMode = 0
}
}, 1000
);
But the problem still hasn't changed. Second time it tries to update, it fails.
Ah, I got it:
diffTotal = trackerBack.appendChild(document.createElement('diffTotal'));
diffFielded = diffTotal.appendChild(document.createElement('diffFielded'));
conductValues("diffTotal", (aValP + aValU - bValP - bValU))
conductValues("diffFielded", (aValU - bValU))
conductValues = function(targetName, targetAssignment) {
document.getElementById(targetName).innerHTML = toBna2(targetAssignment)
}
Those are the lines, which cause the error.
diffFielded is a child of diffTotal. In the first conductValues call, you replace the innerHTML of diffTotal. When you are doing this, you are removing diffFielded, because it's replaces by the new value and then it cannot by found anymore because it does not exist anymore.
I assume diffFielded should actually be another child of trackerBack, so you should do:
diffFielded = trackerBack.appendChild(document.createElement('diffFielded'));
Tip:
Move the style stuff into a css file.

BEGINNER HERE If/else statements with booleans JAVASCRIPT

I am having some trouble with this current lesson on control flow with JavaScript...
The question states:
In this exercise, you will be given a variable, it will be called value.
You will also be given another variable, it will be called greaterThanFive.
Using an 'if statement' check to see if the value is greater than 5. If it is, re-assign the boolean true.
code with stars next to it is the code I was given.
**let greaterThan5 = false;**
if (value > 5 ) {
console.log("That is true");
}
**return greaterThanFive;**
I have tried a number of different ways on how to write the correct code but it obviously is not right.
I tried assigning var value = 10;and then finishing the code as above but it says value has already been assigned. I have tried changing the boolean to let greaterThanFive = true;
The hint only tells me that "should return boolean value equal to 10" and "expected true to be false"
Please help, I have been working on this simple code it may seem for a week and do not want to move on to the next lesson without fully understanding this question.
Thank You!
You have two different variables; greaterThan5 and greaterThanFive.You also have a return statement, which will only work inside of a function.
I believe what you're looking for is something like the following, which passes a value into the function, then checks whether the value is greater than five or not, setting the variable to true inside of the if conditional if it is. The function then returns the greaterThan5 variable's truthiness:
function greater(value) {
let greaterThan5 = false;
if (value > 5) {
greaterThan5 = true;
}
return greaterThan5;
}
console.log(greater(10));
console.log(greater(3));
Which can be further simplified to a simple one-line return statement:
function greater(value) {
return value > 5;
}
console.log(greater(10));
console.log(greater(3));
So, the first clue in the code is the return statement. That means you are likely being asked to write a function that, given some value, checks to see if that value is greater than 5.
Let's define it using your existing code:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
console.log("That is true");
}
return greaterThan5;
}
So right now, we're always going to return false. All you need to do is reassign the value of greaterThanFive if value > 5. So, you can simply do that in your if-statement:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
greaterThan5 = true;
}
return greaterThan5;
}
You can now test your code by calling the function with various values:
isGreaterThan5(1); // returns false
isGreaterThan5(5); // returns false
isGreaterThan5(6); // returns true
And we're done!
I'm wondering if what confused you was the use of let. You might want to read more about var, let, and const.
if (value > 5) {greaterThanFive = true;}

Why won't one part of my javascript function run even though it is syntactically correct?

I'm a programming newbie trying to make a function that asks for a password, but will display an error message if the password attempt is wrong more than five times. I have tried fiddling around with those code a bunch of different ways and it just won't work. I have a variable called count that starts as 0, and each time a wrong password is entered, 1 is supposed to be added to count, and once count is greater than 5, the error message is supposed to be displayed.
document.getElementById("word-checker").onclick = function () {
var count = 0;
var inputValue = document.getElementById("text-input").value;
var secretWord = "password123";
if (count > 5) {
alert("You have had 5 unsuccessful login attempts. You account has been temporarily locked.");
} else if (inputValue == secretWord) {
alert("Your answer is correct!");
document.getElementById("text-input").value = "";
} else if (inputValue!==secretWord) {
count++;
alert("Your answer is incorrect. Please try again.");
document.getElementById("text-input").value = "";
}
}
This is driving me insane. I'm sure it's a simple beginner's mistake though. Any input that would help me understand why this won't work would be met with a lot of gratitude.
You are resetting count to 0 every time the click event is triggered:
document.getElementById("word-checker").onclick = function () {
var count = 0; // <-- button clicked, set the value to zero.
// ...
}
This means that count will never get to 5 (in fact, it never gets to be > 1 either, as when count++ increments the value to 1, it is set back to 0 on the next click). Consequently, the if (count > 5) part of the if statement will never be triggered.
You need to declare count outside of the click event:
var count = 0;
document.getElementById("word-checker").onclick = function () {
// use count here
// ...
}
you are redefining count as 0 every time on the click event. You need to define count as a global outside the function and then ++ on every error.
Also, try to correct your indentation as it helps reading.

Understanding Private Variables (Closure?) in Javascript with specific example

OK, I have tried to use a closure to no avail on the following code to keep a variable private. I am brand new to javascript and have read a number of posts about closures and can still not wrap my head around them. Below, I have a function that, upon each press of a particular button, displays the next word in an array. I want my counter variable ("whatNumber" below) that I am using in this function to not be global but I cannot figure out how. Here is my simple code:
var wordList = ["jumper", "stumpy", "smelly gumdrops", "awesome puttputt", "soilent green"];
var whatNumber = 0;
function changeWord(){
if (whatNumber < wordList.length) {
alert(wordList[whatNumber]);
whatNumber++;
}
};
function changeWord(){
var wordList = ["jumper", "stumpy", "smelly gumdrops", "awesome puttputt", "soilent green"];
var whatNumber = 0;
return function alertWord(){
if (whatNumber < wordList.length) {
alert(wordList[whatNumber]);
whatNumber++;
}
}
};
//to run this
var alertNewWord = changeWord();
alertNewWord() //jumper
alertNewWord() //stumpy
This comes with a bonus of being able to have different functions having different levels of alerting. e.g: if you do another var anotherAlertFn = changeWord() and you call anotherAlertFn() it will result in "jumper". The initial functions (i.e: alertNewWord()) will still have it's own state, i.e: whatNumber === 3 while anotherAlertFn has whatNumber === 1. This can be very useful, imagine a function keeping score for different players in a game. Every player can use the same function without being able to cheat (i.e: change their score) and never affecting other players' scores.

Value from Math.random is causing problems when I call the function inside itself

This script is giving me problems. I've re written it several times but I'm missing something.
'questions' array refers to my objects. These objects are different questions with 'a' always being the correct answer.
The script works fine up to this point. The idea is to increment 'n' from 0 to scroll through my array, and provide the next question when a correct answer is clicked. 'x' is always the correct answer (it always holds 'a').
So I can increment 'n' just fine on correct guess; however, when I call the function 'a()' again, (after my alert 'hi' part), it is causing problems. I want to increment n, and call a() so I get the next question. Then I want to place the correct guess (x) in a random place (ie position 0, 1 or 2.)
Grateful for any help.
var questions = [q0,q1,q2,q3,q4,q5,q6,q7];
var n = 0;
function a(){
var y;
var z;
var x = Math.floor((Math.random() * 3))
if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}
$("#question_holder").text(questions[n].q);
$(".answer_holder").eq(x).text(questions[n].a);
$(".answer_holder").eq(y).text(questions[n].b);
$(".answer_holder").eq(z).text(questions[n].c);
$(document).ready(function(){
$(".answer_holder").eq(x).click(function(){
alert("hi");
n++;
a();
/*this area needs to get the next question by incrementing
n, then generate a different value to x, to place it
in a different position. which it does. however,
in subsequent questions, you can click the wrong answer as if
it's correct, ie not 'a' or 'x'.*/
});
});
};
Your logic is a bit strange here.. what you are trying to do is register a new click event every time a() runs. I think you want to register one click event for all answer_holder elements, and in the event handler check which element this is and handle it accordingly
Notice the following:
$(document).ready(function(){ - the function defined in this handler is supposed to run once your page is loaded.. I don't think you want to use it inside a(). It is usually only used in global scope (outside all functions)
$(".answer_holder").eq(x).click(function(){ - this event handler registers your function depending on the value of x. I suggest you register an event handler for all $(".answer_holder"), without depending on x (in the global scope). And inside that event handler (in the function), you check which element triggered the event (using $(this) - it returns the element that was clicked)
You have the $(document).ready() in the wrong place. Try something like this (caveat: this is completely untested):
function setupQuestion(n) {
var x,y,z;
x = Math.floor((Math.random() * 3))
if(x == 0){y = 1; z = 2}else if(x == 1){y = 0; z = 2}else{y = 0; z = 1}
$("#question_holder").text(questions[n].q);
$(".answer_holder").eq(x).text(questions[n].a).data('answer', 'a');
$(".answer_holder").eq(y).text(questions[n].b).data('answer', 'b');
$(".answer_holder").eq(z).text(questions[n].c).data('answer', 'c');
}
$(document).ready(function() {
var n = 0;
$('.answer_holder').click(function() {
if ($(this).data('answer') === 'a') { // Or whatever is the correct answer
n++;
if (n < questions.length) {
setupQuestion(n);
} else {
// Do something else, the test is finished
}
}
return false;
});
setupQuestion(n);
});
Note that I am not comparing on the text() function but rather the data() function. This is because the text as displayed to the user might be decorated in some way, making comparisons difficult. Simply using the answer index 'a' 'b' or 'c' is clearer.

Categories