Change javascript variable on others script outcome - javascript

I need a way where I can change the variable of a jave script function on the outcome of a different function which gets executed on a input click.
Example of the input:
<input type="image" value="74" onclick="WeaponType(this);GetDamage(74);return false;" class="CompactPistol" src=".\Weapons\Bornheim_No_3_Extended.png" alt="Bornheim No.3 Extended">
<span style="color:whitesmoke">Bornheim No. 3 Extended</span>
(I could also change the 'GetDamage' function input to 'this' instead of the value directly and then just change the function output to use the attribute 'value'. In my case it doesn't really matter as the value of one picture is set.)
My script that needs the variable currently looks like this:
<script id="ResultDamage">
function GetDamage(x) {
document.getElementById("DamageDealt").innerHTML = x;
}
</script>
This ofc only outputs the value of the function. But the value needs to be used in a more complicated calculation
What I f.e. also already tried was this:
<script id="ResultDamage">
function GetDamage(x) {
var z
z = x;
return z;
}
var d = z;
document.getElementById("DamageDealt").innerHTML = d;
</script>
and this:
<script id="ResultDamage">
function GetDamage(x) {
return x;
}
var d = GetDamage();
document.getElementById("DamageDealt").innerHTML = d;
</script>
Which gives me 'undefined'
Any help is appreciated.
As I am quite new to this keeping it simple would probably the best (if there is a simple solution)

Based on comments on the question above...
If you just need to store a value globally on the page then you can declare a variable outside of the function and set its value within any function. For example:
var a = 0;
var b = 0;
// etc.
function GetDamage(x) {
a = x;
// perform a calculation as needed
// write a result to the page as needed
}
In this case the values of a and b are stored at the page level and available to other functions, persist their values between function calls, etc. So you can have separate functions that also use those values for their own calculations.

Related

How to change a variable used as argument for function

I've looked around a little bit, and I haven't found a clear answer as to why when this proceeding code is ran, it returns myInt as 0. I've read posts about how the variable is only changed inside the function, but from my perspective, I don't see any reason why myInt cannot be changed. For refrence, this is in Javascript.
var myInt = 0;
function changeVar(x) {
x += 1;
}
changeVar(myInt);
console.log(myInt);
The reason myInt is not changing is that x has local scope (anything you do to x only affects the value of x inside of changeVar).
Here's how you could change myInt from changeVar():
var myInt = 0;
function changeVar() {
myInt += 1;
}
changeVar();
console.log(myInt);
If you want to change a variable by passing it as an argument, you should pass an object instead:
var myObject1 = {value: 0}
var myObject2 = {value: 10}
function changeVar(x) {
x['value'] += 1;
}
console.log(myObject1['value']);
console.log(myObject2['value']);
changeVar(myObject1);
console.log(myObject1['value']);
console.log(myObject2['value']);
I will expand on the example given by #N.Kern - here is a better example of how to change the initial variable passed in the function:
var myInt = 0;
function changeVar(x) {
return x += 1;
}
var y = changeVar(myInt);
console.log(y);
Now, the reason for this is offered by #Shekhar Chikara in the comment. Essentially, the value you're passing to the function is modified within the local scope of the function, but it's not actually assigned back (or saved in memory) to the globally declared variable. So when you log the original global variable, you get the unchanged value back. Thus, you want to simply save your functions' returned value to it's own variable.
This will get you started on researching more.
Hope this helps.

Changing global Variable from within function

Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well.
Here is the part im working on..:
<script>
var Number = 100; // Number i want changed and to keep changing each button click
function outcome() { // Button calls this function
Number = Number - 1; // Tries to change Global Number.. :/
}
document.write(Number); // Has the Number written in the document
</script>
Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.
Btw, Number is the global reference to the Number constructor so you should use another variable name, lowercase at best.
var num = 100;
function outcome() {
num--;
}
outcome();
document.write(num); // 99
or
<script>
var num = 100;
function outcome() {
num--;
alert(num);
}
</script>
<button onclick="outcome()">Decrease!</button>
(Demo at jsfiddle.net)
You have to call your function:
<script>
var Number=100
function outcome(){
Number=Number-1
}
outcome(); // call the function here
document.write(Number)
</script>
or don't use a function in the first place:
<script>
var Number=100
Number=Number-1
document.write(Number)
</script>

Unable to pass values to a function

I have a function draw_integer(n,s,x,y,plotx) , which draws a integer ,n on HTML5 canvas of size s in the coordinates (x,y), I am calling this function inside another function draw_num() as follows,
(plot0, number and size are the respective id's of canvas, number & size input fields,
function drawnum() is being triggered with an onclick event.)
function drawnum() {
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
The draw_integer function being called under drawnum doesnt get executed, what is the problem I am unable to identify.
using console.debug() returns the appropriate values of number and size as entered by user, also if i use draw_integer(3,100,100,100,plot0) (draw number 3 of size 100) instead of draw_integer(n,s,100,100,plot0) it works .
So that means that there is some error occuring while passing the varaible n and s from drawnum() to draw_integer().
Thinking that this might be due to to the local scope of the variables , I tried this.
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
function drawnum() {
console.debug(n,s);
draw_integer(n,s,100,100,plot0); // this doesn't get executed
}
function draw_integer(n,s,x,y,plotx){ //lots of code }
But that didn't work either.
can you help me out or suggest a better way to solve this problem .
var n = document.getElementById('number').value;
var s = document.getElementById('size').value;
The variables n and s above are Strings and not Numbers. You need to either use parseFloat or parseInt to convert it.
var n = parseInt(document.getElementById('number').value, 10);
var s = parseInt(document.getElementById('size').value, 10);

Help with adding variable to self and random number (javascript)

I am making a simple dice roller, which seems like a good first project to me, and may help others learn javascript as well, and when you roll a die (with a button), it is supposed to add to the total (there is a clear button), but it says NaN. Here is my code:
<html>
<body>
<script type="text/javascript">
function load()
{
document.getElementById("press").value=" "
var x=0
}
function d6()
{
var x=x+(Math.floor((Math.random() * 6) + 1));
document.getElementById("press").value=(x)
}
load()
</script>
<input type="button" value="Roll d6" onclick="d6()"/>
<input type="text" id="press"/>
</b>
<input type="button" value="Clear" onclick="load()"/>
</body>
</html>
Help would be greatly appriciated.
Thanks!
This is happenning because variable x is not initialised when you are using it in d6(). The scope of the 2 functions is different.
You need x to be a global variable. For that, use the following code structure:
x = 0
function load() { ... }
function d6() { ... }
Remember that when you declare a variable with the keyword 'var' preceding it, the variable is considered local. A variable without a 'var' is considered global.
Your x variables are local to the functions. change x to be a global variable:
var x;
function load() { ... }
function d6() { ... }
When using JavaScript it is important to consider the scope of names and values. Consider the difference between this:
var x = 2;
function assignX(v) {
x = v;
}
print(x); // 2
assignX(3);
print(x); // 3
and this:
function assignX(v) {
var x = v;
}
print(x); // undefined
assignX(3);
print(x); // undefined
In the first example x exists in the global scope which encloses all names and values. In the second example x only exists within the function assignX.

Using a global variable in JavaScript

How do I do this?
My code is something like this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
var number = '10';
alert('' + [number] + '');
}
The first alert always returns 'old number was: ' and not 10. Shouldn't it return 10 on both alerts on the second function call?
By using var when setting number = '10', you are declaring number as a local variable each time. Try this:
var number = null;
function playSong(artist, title, song, id)
{
alert('old number was: ' + [number] + '');
number = '10';
alert('' + [number] + '');
}
Remove the var in front of number in your function. You are creating a local variable by
var number = 10;
You just need
number = 10;
The problem is that you're declaring a new variable named number inside of the function. This new variable hides the global number variable, so the line number = 10 assigns only to this new local variable.
You need to remove the var keyword from var number = 10.
Like in C, you need to define your variable outside of the function/method to make it global.
var number = 0;
function playSong(artist,title,song,id)
{
alert('old number was: '+[number]+'');
number = '10';
alert(''+[number]+'');
}
Let me explain in detail. To declare global variables and local variables in JavaScript
var firstNumber = 5; // Local variable
secondNumber = 10; // Global variable or window object
When your program is like this
var number = 1;
function playSong() {
alert(number);
var number = 2;
alert(number);
}
As per the JavaScript compiler, all declarations/initializations of variables will move to the top. This concept is called hoisting.
As per the compiler, the program will execute like:
var number; // Declaration will move to top always in Javascript
number = 1;
function playSong() {
var number;
alert(number); // Output: undefined - This is a local variable inside the function
number = 2;
alert(number); // Output: 2
}
If you need to access the global variable inside the function, use window.number.
var number = 1;
function playSong() {
var number = 2;
alert(window.number); // Output: 1 - From a global variable
alert(number); // Output: 2 - From local variable
}
You can also access it in any function like window.number, after removing var inside the function.
I’ve come across this answer in 2020 and after searching some more online I have found that apparently in the JavaScript definitions if you place variables outside of functions or even create a file called globals.js and just put all your globally required variables in that file, make that file the first user .js file in your script tags after jQuery and any other plugins you need, globals will load before your other scripts and allow you to call variables from globals.js within any script on the page.
W3C JavaScript Scope
I have tested this theory within a PHP application that I am building and I have been able to call variables from the globals.js file within a page that is loaded via Ajax to a jconfirm dialog for a troubleshooting wizard to set up the return values for when the dialog is closed.

Categories

Resources