Javascript: why will variable work locally but not globally - javascript

I am new to JavaScript and am having trouble understanding why a variable can be used when it is declared inside a function (locally) but not outside (globally).
For example: https://jsfiddle.net/Buleria28/kqu69aqt/
Or if it is easier to view here. Why will this work?:
function numDisplay (){
var e = document.getElementById("numVal").value;
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
And why won't this work?:
var e = document.getElementById("numVal").value;
function numDisplay (){
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
The corresponding HTML is:
<form method = "POST">
<fieldset>
<label for="numVal">Enter Number Value:</label>
<input type="number" id="numVal" name="numVal"/>
</fieldset>
</form>
I am curious because I would like to use the user input for found in the variable "e" in different functions.

In the case of:
var e = document.getElementById("numVal").value;
function numDisplay (){
document.getElementById("show").innerHTML = e;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
e is computed at run time, so the value is nothing which is then stored as e (your starting value.)
However making a slight change to your code can make this work.
var e = document.getElementById("numVal");
function numDisplay (){
document.getElementById("show").innerHTML = e.value;
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);
In this example e's value is found on each click, which will then display the current value and set that as the innerHTML of your 'show' element.

The problem is when the script code runs. If you set a global variable like this and it is null
var e = document.getElementById("numVal").value;
Then it probably executed before the browser created that part of the page.
You can use global variables that you set to a number or string that way since that does not depend on the page / document:
var number_of_puffins = 11;
If you want a variable to point to a part of the document you need to have a function to set it after the page exists.
<body onLoad="setglobals();">
Be careful about using code like your example since the page can change if you add or delete items.

Both of your options work as planned.
The difference is the value.
When you run the script for the first time, there is no value in the input, but when you run it inside the function, it alredy has value.
You can change when you are calling the value, ie:
var e = document.getElementById("numVal"); //Remove the .value
/*why won't having the variable above rather than inside
the function work?*/
function numDisplay (){
//var e = document.getElementById("numVal").value;
document.getElementById("show").innerHTML = e.value; //use it here.
}
document.getElementById("calcBtn").addEventListener("click",numDisplay);

The function numDisplay() doesn't work correctly when e is a global variable because numDisplay() is triggered when #calcBtn is clicked.
Let's say you enter the number 5 in the input field and click the "Show Number" button. This runs numDisplay() and sets the HTML in #show to e. However, e never got the number 5. It still has an empty value which was assigned to it when you loaded the page. For it to keep getting new values each time you click the button, var e = document.getElementById("numVal").value; needs to be inside the function.

Related

GTM javascript does not fill variables

I am trying to use predefined variables for a simple GTM javascript macro, however, the variables do not load. Why is my code not loading the variables?
code:
function () {
var value = {{Click URL}};
var begin = value.indexOf(":")+1;
var end = value.substr(-1);
return value.slice(begin,end);
}
Just a shot in the dark, but the click variables are not enabled by default. Check if they are enabled in variables/built in variables:
You'd need to set the checkbox in front of Click URL.
In the end I solved it by leaving out the "end" variable (slice automaticlly uses the last character if you do not feed it the second argument). It looks like this now:
function () {
var value = {{Click URL}};
var begin = value.indexOf(":")+1;
return value.slice(begin);
}

jQuery accessing updated values from variables on different events

I have a function which copies the values of a group of inputs to another group of inputs if the user clicks a button.
The function works fine but I'm having trouble with the vars I'm using to get the information. I want to use global variables because I want to use the same variables later on but it only works when I wrap those vars inside the function.
I've posted the two scenarios where it's working and not working below. Can anyone explain why I cannot access the correct value at that given time using a global variable?
EDITS: The 3 elements #admin-name, #admin-email and #admin-number are all present in the DOM when the script is called, as I am doing everything with document ready. I understand that when the script first runs these values will be blank because they haven't been filled out by the user yet. What I don't understand is why can't jQuery get the value once it has been filled out and I call the variable on the click function.
Not Working
var contactName = $('#contact-name').val();
var contactEmail = $('#contact-email').val();
var contactNumber = $('#contact-number').val();
$(".step-two .copy-details").on('click', function(){
$('#admin-name').val(contactName);
$('#admin-email').val(contactEmail);
$('#admin-number').val(contactNumber);
});
Working
$(".step-two .copy-details").on('click', function(){
var contactName = $('#contact-name').val();
var contactEmail = $('#contact-email').val();
var contactNumber = $('#contact-number').val();
$('#admin-name').val(contactName);
$('#admin-email').val(contactEmail);
$('#admin-number').val(contactNumber);
});
Man I struggled with this one, this post helped flesh it out for me, jQuery Global Variable. The problem is the variable called in the click function was still getting the original value of 0. To make the variable update when a new value is added you need to declare it and then wrap it in a change function like so:
JS
// declare the variable
var contactName;
// wrap it in a change function so the value updates
$('#contact-name').on('change', function(){
contactName = $('#contact-name').val();
});
// use the variable inside the function and it will show the updated value
$('.step-two').on('click', 'button', function(){
$('#admin-name').val(contactName);
console.log('contactName = ' + contactName);
});

JS Function calling displaying odd text & not working more than once

I have a problem, when I run my function "addMoney(amount)" (shown below) it works and shows the following: 100[object HTMLButtonElement]
My question is this, is there a way to get rid of the [object HTMLButtonElement] while keeping the number from moneyAmount when the function is called? And additionally, is there a way to call the function multiple times and add the money accordingly? As it only works the first time I call it, calling it more than once with the same or different amounts of moneyAmount displays no more or no less than what displays the first time.
My HTML:
<li class="item_shown" id="money">Shrill: <button class="moneyButton" id="moneyAmount">0</button></li>
Calling the function in HTML:
<a class="button" onclick="javascript:addMoney('100');">Add 100 Money</a>
My JS Function:
function addMoney(amount) {
document.getElementById('moneyAmount')
var newBalance = amount + moneyAmount;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
The text inside an element is considered to be a text node and since the button node has no other children, is the button node's first child. The text node's value (in this case "0") is the value of its nodeValue property. Assigning a new value to the nodeValue will change the text displayed. So in your case the following code should work:
function addMoney(amount) {
var node = document.getElementById('moneyAmount');
var textNode = node.childNodes[0];
var moneyAmount = parseInt(textNode.nodeValue, 10);
textNode.nodeValue = amount + moneyAmount;}
In your JavaScript, + moneyAmount; does not do anything. It returns what you see: [object HTMLButtonElement].
I think you want to add some numbers but it's not yet completely clear to me what you're trying to achieve. Could you elaborate?
Chris
EDIT:
Thank you for clarifying your question.
Try updating your function like this:
function addMoney(amount) {
var oldBalance = document.getElementById('moneyAmount').value;
var newBalance = amount + oldBalance;
document.getElementById('moneyAmount').innerHTML = newBalance;
}
Try to find value by document.getElementById('moneyAmount').innerHTML and use some global variable say total_value to store retrieved value and then for each function call try to add the retrieved value to the previously stored value.

How do you add a input element to a variable

I input a number into a textbox.
I want to know how do you cast this number to a declared variable:
For Example:
<body>
Please Enter value number 1: <input type = "text" id = "value1"></input>
<button onclick = "Display()">Display</button>
<p id = "Paragraph"></p>
<script>
The Question is here:
var a = document.getElementById("value1").value;
The statement above is what i want to know to do.
function Display()
{
document.write(a);
}
</script>
</body>
I am new to javascript, and i'm trying to learn so sorry if the question is a bit basic but im struggling to get this right.
I guess you mean something like this:
function Display()
{
var a = document.getElementById("value1").value;
document.getElementById( 'Paragraph' ).innerHTML = a;
}
With your code the variable a is just assigned, when the script is executed the first time. It is not a pointer to the value, but just grabs the value once. So if you want to use it, when clicking the button, you have to get it inside the executed function.
Don't use document.write() like this. If you want to display something at runtime innerHTML is a better choice!
Assign a inside your function:
function Display()
{
var a = document.getElementById("value1").value;
console.log(a);
}
Also, <input /> tags do not require a closing </input> tag.

How do I write a mouse down event in JavaScript?

This is very basic I'm sure to JavaScript but I am having a hard time so any help would be appreciated.
I want to call a function within a for loop using the mouseDown event occurring within an object's second child node. The part italicized is my attempt to do this. The swapFE function is still a work in progress by the way. And one more thing is when I put the italicized part in the swapFE function everything works properly but when I put it in the for loop it doesn't all show up. I don't know why. I am basically trying to swap French phrases for English ones when I click the phrase with my mouse.
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
var swapFE = document.getElementsByTagName("phrase");
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
}
/* see "function_swapFE(phrase,phrasenum);" below. The expression to call function swapFE
is located underneath "function swapFE(e)" because although the directions said to put the
"run swapFE" within the for loop it did not work properly that's why I put it beneath the
"function swapFE(e)".*/
function swapFE(e) {
var phrase = eventSource(e);
var phasenum = parseInt(1) = [1].innercontent.previousSibling;
phrase.node.previousSibling.onmousedown=swapFE
function_swapFE(e)(phrase,phrasenum);
}
}
If you have questions let me know.
Thanks for your help.
With this, you are creating a local variable named swapFE;
var swapFE =
document.getElementsByTagName("phrase");
Then with this you are setting this var as a mouseDown
phrases[i].childNodes[1].onMouseDown =
swapFE;*
That's not right... onMouseDown should be set to a function name, not a local variable of that name. So you should probably rename the local var to something else. That will at least get you closer to a solution.
I can only make a couple of guesses at what might be failing with your source code. Firstly, the following code assumes that all <p> tags have at least 2 child elements:
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
If any <p> tags on your page have less than 2 child elements, an error will be thrown and script execution will halt. The best solution for this would be to add a class attribute to each <p> tag that will contain the elements you're looking for. Alternatively, you could just check for the existence of the second childnode with an if statement. Or you could do both.
Secondly, like all events, onmousedown should be declared in lowercase. Setting onMouseDown will not throw an error, but instead create a custom property on the element instead of attaching an event handler.
Finally, the following code:
var swapFE = document.getElementsByTagName("phrase");
will locally override the global function swapFE for that function, replacing it with a variable instead.
This is how I might write your setupTranslation function:
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
// rename the swapFE var as outlined below
var swapFENodes = document.getElementsByTagName("phrase");
var cNode; // set up an empty variable that we use inside the loop
for (i = 0; i<phrases.length; i++) {
/* Check for the existence of the translationPhrase class
in the <p> tag and the set the cNode var to childNodes[1]
and testing for its existence at the same time */
if (cNode.className != "translationPhrase"
|| !(cNode = phrases[i].childNodes[1]))
continue; // skip to the next iteration
phrases[i].number = i;
cNode.innerHTML = french[i];
cNode.onmousedown = swapFE; // Changed onMouseDown to onmousedown
}
}

Categories

Resources