Im opening html file from js function:
function initCategoryPage(url){
var catUrl=url;
window.open("category.html");
}
I putted this script in "category.html" but it doesnt get the var catUrl:
<script>
myUrl = window.opener.catUrl;
alert(myUrl)
id=1;
firstTime=true;
ArticlesBlock();
</script>
how can I pass it to category.html?
The reason it can not read it is because the variable is not global. The scope is limited to that method.
function initCategoryPage(url){
window.catUrl=url; /*make it global*/
window.open("category.html");
}
A better solution would be to pass it as a querystring or use postMessage to get the value.
Related
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
So as you might know, Razor Syntax in ASP.NET MVC does not work in external JavaScript files.
My current solution is to put the Razor Syntax in a a global variable and set the value of that variable from the mvc view that is making use of that .js file.
JavaScript file:
function myFunc() {
alert(myValue);
}
MVC View file:
<script language="text/javascript">
myValue = #myValueFromModel;
</script>
I want to know how I can pass myValue directly as a parameter to the function ? I prefer to have explicit calling with param than relying on globals, however I'm not so keen on javascript.
How would I implement this with javascript parameters? Thanks!
Just have your function accept an argument and use that in the alert (or wherever).
external.js
function myFunc(value) {
alert(value);
}
someview.cshtml
<script>
myFunc(#myValueFromModel);
</script>
One thing to keep in mind though, is that if myValueFromModel is a string then it is going to come through as myFunc(hello) so you need to wrap that in quotes so it becomes myFunc('hello') like this
myFunc('#(myValueFromModel)');
Note the extra () used with razor. This helps the engine distinguish where the break between the razor code is so nothing odd happens. It can be useful when there are nested ( or " around.
edit
If this is going to be done multiple times, then some changes may need to take place in the JavaScript end of things. Mainly that the shown example doesn't properly depict the scenario. It will need to be modified. You may want to use a simple structure like this.
jsFiddle Demo
external.js
var myFunc= new function(){
var func = this,
myFunc = function(){
alert(func.value);
};
myFunc.set = function(value){
func.value = value;
}
return myFunc;
};
someview.cshtml
<script>
myFunc.set('#(myValueFromModel)');
myFunc();//can be called repeatedly now
</script>
I often find that JavaScript in the browser is typically conceptually tied to a specific element. If that's the case for you, you may want to associate the value with that element in your Razor code, and then use JavaScript to extract that value and use it in some way.
For example:
<div class="my-class" data-func-arg="#myValueFromModel"></div>
Static JavaScript:
$(function() {
$('.my-class').click(function() {
var arg = $(this).data('func-arg');
myFunc(arg);
});
});
Do you want to execute your function immediately? Or want to call the funcion with the parameter?
You could add a wrapper function with no parameter and inside call your function with the global var as a parameter. And when you need to call myFunc() you call it trough myFuncWrapper();
function myFuncWrapper(){
myFunc(myValue);
}
function myFunc(myParam){
//function code here;
}
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.
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);
}
I am new to javascript & jQuery. I'm trying to create a feature for my site that let's people display badges they have earned on their own site (and I would supply a bit of code they could just copy/paste). I had someone help me with the javascript and I have it working perfectly, but I can't find any jQuery documents that explains it to me?
<script type="text/javascript">
(function(id) {
// include js via php file with the id in as a parameter
})("myid");
</script>
The id is passed in the area labeled "myid", in jQuery can you pass in a static variable this way? When I try to delete ("myid") and change it to var id = 'myid', the function no longer works.
The occurrence of "myid" in the code you are showing is not a static variable. It is a string literal that is being passed as an argument to an anonymous function. The anonymous function is declared and then is immediately getting called.
If you are wondering why the programmer wrote the JavaScript the way they did. The following might help.
Both of the examples below will display "myid" in an alert:
Example 1:
<script type="text/javascript">
var id = 'myid';
alert(id);
</script>
Example 2:
<script type="text/javascript">
(function(id) {
alert(id);
})('myid');
</script>
The first example declares "id" as a variable. It is a global variable and is actually added as a property to the window object. The second example defines an anonymous function and immediately calls it, passing in 'myid' as the value of the "id" parameter. This technique avoids using a global variable.
Of course, you could also avoid the global variable by doing the following:
<script type="text/javascript">
(function() {
var id = 'myid';
alert(id);
})();
</script>
If you stick "myid" in a variable and then pass in that variable, it'll work. Like this:
var memberID = "myid";
(function(id) {
// include js via php file with the id in as a parameter
})(memberID);
If you say this...
(function(id) {
// include js via php file with the id in as a parameter
})(var id = 'myid');
...you're attempting to stick a variable declaration in a function call, which won't work. That's why declaring the variable above and apart from the function call won't throw any errors.