Adding numbers within a function - javascript

So what i'm trying to do is to call a function using onclick and when that function activates the total will add 5 on to itself e.g. 0+ 5 = 10, then when called again it will remain at 5 and do 5 + 5 = 10, 10 + 5 = 15 etc.
var total = 0;
function addFive(){
var a = 0;
var b = 5;
var c = a + b;
alert(c)
var total = total + c;
alert(total)
}
<input type="button" value="£5" onClick="addFive()" id="butFive">

var total = total + c;
Using var declares a new variable (with the same name) in the current scope. It masks the total in the wider name.
Don't use var here.
var total = 0;
function addFive() {
var a = 0;
var b = 5;
var c = a + b;
total = total + c;
console.log(total)
}
<input type="button" value="£5" onClick="addFive()" id="butFive">

Variables in javascript has function scope. It means, that defining variable inside function hides global definition. In your case, first declared total variable has global scope and then you hide it inside your function.
In fact, you are assigning value to local, each time created variable.
To solve your problem, try:
total = total + c;

Related

I would like to know how I can make the "namePrinter" loop function work well?

I was trying to get javascript to print the result of the "generateName" function at least 10 times when I press a button in the html, so i tried a loop inside the function that generates the names and but it didn't work then I separated the loop and wrote it in the function "namePrinter" and create the global variable "names" to store the results of the function "generateName"
but I don't know what part of this whole process is wrong, I already reviewed other questions that were made in this forum but I didn't find an answer either
JS:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length + 2)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length +2)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
for (var i = 0; i < 10; i++) {
text[i].innerHTML(`${names}`)
}
return namePrinter;
}
innerHTML is not a function, it's a property. So, in the loop use text.innerHTML += name
However, if it's a <textarea> element, then you need to use value property instead:
//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;
document.getElementById("elvenFemButton2").onclick = namePrinter2;
//cutting characters function
function capFirst(string){
return string.charAt(10).toUpperCase() + string.slice(1);
}
//Randomizer
function getRandomInt (min,max){
return Math.floor(Math.random() * (max-min)) + min;
}
//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
var elfLastName2 = ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length)]);
return elfFemNameGenerator;
}
//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();
var names2 = [];
// this should print the name at least ten times but no
function namePrinter(){
var text = document.getElementById("textArea");
text.value = ""; //clear previous result
for (var i = 0; i < 10; i++) {
text.value += names;
}
}
function namePrinter2(){
var text = document.getElementById("textArea");
names2.length = 0; //clear array
for (var i = 0; i < 10; i++) {
names2[names2.length] = generateName();
}
text.value = names2;
}
<textarea id="textArea"></textarea>
<button id="elvenFemButton">generate names</button>
<button id="elvenFemButton2">generate different names</button>
This however as you can see will print the same name 10 times, if you need generate 10 names and store them globally, than you'll need save them in the array instead.
P.S.
Unrelated, but elfLastName2[getRandomInt(0,elfLastName2.length +2)] is wrong, you can't get value from an index that is larger than length of the array (aka +2 is wrong)

How do I take a variables prior value and subtract it from the final value if the total value of the variable cannot exceed a certain amount?

example:
var num = 20;
var sub = 6;
var add = 10;
num = num - sub;
num = num + add;
if (num>20){
num = 20;}
console.log("X was added to var num");
How can I get the console log to say that var num really only had 6 added to it before it hit it's max value?
Your question isn't very clear. Do you need to keep a log of what num is?
I would reccomend an array for that:
let log = [];
Then before you change num:
log.push(num);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If you just want the console to display the value of a variable there's several ways:
console.log(add, " was added to var num");
console.log(add + " was added to var num");
console.log(`${add} X was added to var num`);
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Javascript SyntaxError: missing ; before statement (after for loop)

I keep getting this error and it's confusing me..
function calculate(){
var n = document.getElementById("noOfCourses").value;
for(var i = 0 ; i < n ; i++) {
var course[i] = document.getElementById("GPA" + i+1).value;
var hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
var product[i] = course[i] * hours[i];
}
}
Basically you need to declare and initialise arrays before using them.
function calculate(){
var n = document.getElementById("noOfCourses").value,
course = [], // declare and init before
hours = [], // declare and init before
product = []; // declare and init before
for(var i = 0 ; i < n ; i++) {
course[i] = document.getElementById("GPA" + i+1).value;
hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
product[i] = course[i] * hours[i];
}
}
The var keyword is used to declare new variables, and optionally initialize them. It's not used in ordinary assignments. And it makes no sense to include an index in the variable being declared -- indexes are used to access the contents of an array, not declare anything.
function calculate(){
var n = document.getElementById("noOfCourses").value;
for(var i = 0 ; i < n ; i++) {
course[i] = document.getElementById("GPA" + i+1).value;
hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
product[i] = course[i] * hours[i];
}
}

Setting the value in a for loop in Javascript

I have a for loop that i need to increase the value of on each iteration, and a few examples of what I have tried so far. I need to increase the value of tp on each loop through:
for (var t = 9; t < 20; t++) {
//Tried the below:
var timePeriod = report_data[i] + '.tp' + t.toString();
venues[i].scan_times[t] = timePeriod;
//and:
venues[i].scan_times[t] = report_data[i].tp + t;
}
The manual way of doing it, which I am trying to use the for loop to accomplish:
venues[i].scan_times['9'] = report_data[i].tp9;
venues[i].scan_times['10'] = report_data[i].tp10;
....
venues[i].scan_times['19'] = report_data[i].tp19;
venues[i].scan_times['20'] = report_data[i].tp20;
In javascript you can always access attributes in two ways: with bracket notation and dot notation
var myObj = {};
// those 2 lines are equivalent
myObj.a = 1;
myObj['a'] = 1
If you want to dynamically access some attributes you can use whatever you want inside the brackets.
// those 2 lines are equivalent
myObj['a' + 4] = 1;
myObj.a4 = 1;
In your case you can write
for (var t = 9; t < 20; t++) {
venues[i].scan_times[t] = report_data[i]['tp' + t];
}

How to combine variables of 2 events into one as sum of both. jquery

Basically I'm trying to create simple price calculator. There are 2 functions which calculates price on select event. How I can sum values of these 2 functions into one, and then add it to ".sum" div ?
var xx = j('select[name="miestas"]').change(function(){
var kainos = {"vln":"55", "kns":"150"};
var val = j(this).find(":selected").text();
kaina1 = kainos[val];
return kaina1;
});
var zz = j('select[name="vardas"]').change(function(){
var kainos = {"vln":"35", "kns":"30"};
var val = j(this).find(":selected").text();
kaina2 = kainos[val];
return kaina2;
});
j('select').change(function(){
j('.sum').html(zz + xx); });
Don't return anything from those functions, assign the result to some global variables:
var xx;
var zz;
and inside the handlers:
...
xx = Number(kaina1);
...
zz = Number(kaina2);
Working example:
http://jsfiddle.net/txkmD/1/

Categories

Resources