Passing a value from a javascript to another js file - javascript

My code is...
<script type="text/javascript">
function changeval() {
$total = parseInt($("#small").val()) + parseInt($("#medium").val());
}
</script>
How can I pass '$total' to another js file, say main.js.

Call changeval function from another file, save/use returned value.
function changeval() {
return parseInt($("#small").val()) + parseInt($("#medium").val());
}
Or have one global variable save value inside the same variable and access it from another file.

Make sure that $total is assigned to the global scope and make sure the script where you want to use it is below the script where you assign it. Be careful about polluting the global scope too much because it can make code that is very tricky to debug and can cause strange errors if you overwrite a native global variable.

Related

Node.js run file inside another file

this is my current code
function includeClass(classname, ctx) {
var txt = fs.readFileSync("socket.io/" + classname + ".js");
return txt;
}
//define globals here
var _PLAYERS = {};
var _SPAWNPOINTS = [];
vm.runInThisContext(includeClass("vector"));
vm.runInThisContext(includeClass("class"));
vm.runInThisContext(includeClass("connectionHandler"));
vm.runInThisContext(includeClass("game"));
But that way, class.js file can't access variables from global scope or other files. because now i get errors like, _PLAYERS or require is undefined. I've tried eval() too, but it didn't do anything at all.
How can I run these js scripts in main script so they get interpreted as 1 whole?
https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options:
Running code does not have access to local scope, but does have access to the current global object.
Your _PLAYERS variable is not truly global, it is local to your script. As well as some other variables (like require) which are also in the module scope.
You can try to assign the needed variables to global object, however, I am not well aware what side effects and complications may follow.

trying to use variables in javascript outer the function scope

i m using node-red and i m injecting some json variables, i can only see them in function scope, how can i use them outer the function.
i've tried angularjs controller but it didn't work, maybe i did not used it correctly
<!DOCTYPE html>
<html>
<body>
<div>{{msg.payload}}</div>
<div>{{value}}</div><br>
<div>{{value1}}</div><br>
<div>{{value2}}</div><br> // i can see the contents
<md-button ng-click="send({payload:action()})">
</md-button>
<script>
(function(scope) {
scope.$watch('msg', function(msg) {
if (msg.payload.image) {
scope.value2 = msg.payload.image;
}
if (msg.payload.text) {
scope.value1 = msg.payload.text;
}
if (msg.payload.volume) {
scope.value = msg.payload.volume;
}
scope.action = function() {
return [scope.value, scope.value1, scope.value2];
}
});
})(scope);
</script>
</body>
</html>
Variables are only valid and accessible in the scope where they were created (and in "child-scopes").
If you want to have some global variable, you can just create a "global variable" (just google).
But since you are using Angular (though the old "angularjs" and not the new "Angular" version), there are better ways. In Angular (the new one, don't know about the old one) you can create and use something called "service". Those are some sort of global accessible object that can hold many variables and stuff to be used elsewhere in the code.
BUT: Depending on your use-case here, you may also create the variables on the outer angular-component and insert/pass them into the child-component. This way both can use and access it. Read more about binding/2-way-binding for that purpose.

Retrieving Variable From A Javascript File

My question is how to share a variable between two different javascript files. I am creating a form that transfers the value to a different page, which alerts that variable. I have 2 html files (index.html and form.html) as well as 2 javascript files (form.js and index.js). So basicly I want to share the variable theNick from form.js to index.js to display it using alert(). If this is not possible, is there another way to do this?
form.html:
<input type="text" id="Nick" placeholder="Nickname">
<a id="btn" onclick="submit()" href="index.html.">Submit</a>
form.js:
function submit(){
var theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
index.html:
<button onclick="callNick()">Click Me to view your Nickname.</button>
index.js:
function callNick(){
???????
alert(theNick); //I want to get access to this variable from form.js
}
By using the var keyword you are doing exactly the opposite. If you want to share something the easiest thing would be to bind the variable to the window object like this: window.theNick = ... and use it like alert(window.theNick).
It is sort of possible.
First of all you need to make certain that your HTML loads both JavaScript files. There isn't really a way for them to import each other, so the HTML must load both scripts.
Secondly, you need to modify your function submit to use a global variable. Global variables are initially defined outside the scope of a function. The function callNick is already looking for a global variable.
However, the submit function is defining its own, local variable because of the keyword var being used inside the function scope. Change it like so:
// Set global variable
var theNick;
function submit(){
// Use global variable
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
See this article for further information.
http://www.w3schools.com/js/js_scope.asp
You could just declare the variable outside of the function
var theNick; // you could omit this entirely since it will be declared in
// global scope implicitly when you try to assign it in the function
function submit(){
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
}
javascript does not care about which files declarations are made but in which scope.
By placing the variable in global scope you'll be able to access it everywhere.
Global variables are not the best coding strategy but this should help you with the concept
It seems like you need to store the variable in the local storage object of the window object, this way you can set its value on the first page and retrieve it on the second.
page 1
window.localStorage.setItem("yourVariable", "yourValue");
page 2
var myVar = localStorage.getItem("yourVariable");
Only one 'caveat': this is a html5 feature, so it comes with limitations, check this link for more info.
You can pass your variable into the url, using the ?yourVar= GET mark :
form.js
function submit(e){
var theNick = document.getElementById("Nick").value; //retrieves theNick
e.target.href+='?n='+theNick; // set the href of your anchor with your variable
}
form.html
<input type="text" id="Nick" placeholder="Nickname">
<!-- We pass the event object into our function as a parameter -->
<a id="btn" onclick="submit(event)" href="index.html">Submit</a>
index.js
function callNick(){
// get the variable from the current location
var theNick = window.location.href.split('?n=')[1];
alert(theNick);
}
index.html
<button onclick="callNick()">Click Me to view your Nickname.</button>
▶︎ Plunker where "form" has been changed to "index" and "index" to "result".
Note :
To pass multiple variables, you can use the & delimiter, and then use the window.location.search property as done in this CSS-tricks article.
▶︎ Multiple vars plunker

Why doesn't this function modify the global version of the array?

I have defined a variable in what I think is global scope. I want to modify the same variable inside a function that lives in a class, then use it later to export as json data.
The function is called by the xataface api, so I'm not sure I can mess with the function signature to do something like passing by reference. I've thought I might access the instance of this action class in the javascript embedded php, but I don't know how to ask the api for it, nor am I confident of its lifetime. It seems like a global variable may be the way to go. In any case, I want to know:
Why is not the global instance of $dataset1 the one being modified inside the function?
Why doesn't the call to array_push put anything on either array?
<?php
//non-dynamic data delcared in global scope. This is picked up later
//in a php block embedded into javascript
$dataset1 = array(array("label"=>"c120","data"=>"1"),
array("label"=>"c150","data"=>"10"),
array("label"=>"camp","data"=>"7"));
class actions_time_in_type
{
function handle(&$params)
{
$this->app =& Dataface_Application::getInstance();
//The Query
$result = mysql_query("SELECT typeDes, total
FROM myTable", $this->app->db());
//reserch leads me to believe that this *should* make all subsequent
//references to $dataset1 use the global instance
global $dataset1;
//experimenting with appending more non-dynamic data
//for some reason, this syntax does not seem to touch $dataset1
array_push($dataset1, array("label"=>"dv20","data"=>"1"));
//This syntax is working, but $dataset1 is not the same as the global
//$dataset1. Prepending "global" here seems to crash the script
$dataset1[] = array("label"=>"pa18","data"=>"5");
while($row = mysql_fetch_assoc($result))
{
//append data to the array, again, this is not hitting
//the global instance of $dataset1
$dataset1[] = array("label"=>$row['typedes'],"data"=>$row['total']);
}
mysql_free_result($result); //Frees the result after finished using it
//diagnostic dump to see what we've got
//This shows that we've constructed the dynamic data set, but it
//seems to be scoped only to this function and does not make it into
//javascript.
var_dump($dataset1);
}
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript">
$(function () {
//This is getting only what was done original init of $dataset1, nothing that
//happened in the function made a difference
var dataset1 = <?php echo json_encode($dataset1); ?>;
});
</script>
It appears this is indeed a problem with execution order. Since the manipulation of the data happens within a class definition which in turn is called by the api, there appears to be no assurance that the global definition of the data will be in scope when it is time to manipulate the data, or that it will have been manipulated when the data is re-used further down.
For the interested reader, I was able to get the api developer to demonstrate the proper way of integrating javascript with the api calling the in-class function:
https://groups.google.com/forum/#!topic/xataface/l6qBzxF1vrc

Can't access a global variable

I'm trying to access a global variable in testGlob1, however I'm not able to do so:
var displayVar;
function globVariable(){
displayVar="2";
}
function testGlob1(){
alert(displayVar);
}
You aren't showing how your variable is being assigned a value. Is globVariable() being called on load of the document? Im sure this would work:
var displayVar=2;
function testGlob1(){
alert(displayVar);
}

Categories