Trying to pass i variable to test function that must change value:
<HTML>
<HEAD>
<TITLE> Welcome to my site</TITLE></HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
var atl = new ActiveXObject("ATL.Object.1");
var i =6;
atl.test(i);
document.write(i);
</SCRIPT>
</BODY>
But in output I still have 6. How to pass value by reference?
On Javascript pass by reference does not exist. You can use an object to pass and it works like passing by reference.
eg :
var atl = new ActiveXObject("ATL.Object.1");
var i = { value: 6};
//if ActiveXObject does not work with your Object, than you need to make an adapter or store the value back to i
atl.test(i);
document.write(i.value);
Related
I wanted to code simple function to change the title of the document.
First I tried this code:
<head>
<meta charset="utf-8">
<title>Zmeň mě!</title>
</head>
<body>
<input type="text" id="newTitle">
<button type="button" onclick="titleChange()">sub</button>
</body>
<script type="text/javascript">
var title, newTitle;
title = document.title;
newTitle = document.getElementById("newTitle").value;
function titleChange(newTitle) {
title = newTitle;
}
</script>
That didn't work so I was randomly changing it to this:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Zmeň mě!</title>
</head>
<body>
<input type="text" id="newTitle">
<button type="button" onclick="titleChange()">sub</button>
</body>
<script type="text/javascript">
function titleChange(newTitle) {
document.title = document.getElementById("newTitle").value;
}
</script>
Why the second one works, but the first one doesn't?
Thank you so much for the answers.
Why the second one works, but the first one doesn't?
There are two parts to the problem:
Where you are getting the new value from.
Where you are assigning the value to.
Getting the new value
In
function titleChange(newTitle) {
title = newTitle;
}
you are getting the new value from the newTitle parameter. But looking at the callsite (onclick="titleChange()") you are never passing a value for the parameter.
Now, above the function you are defining a variable with the same name:
newTitle = document.getElementById("newTitle").value;
This doesn't have any effects for two reasons:
The parameter newTitle shadows the variable with the same name, thus the value of the variable is never read.
var foo = 42;
function bar(foo) {
console.log(foo);
}
bar(21); // logs 21, not 42
The assignment happens only once at page load. At this point in time the input field doesn't have a value yet. Changes to the field later on won't magically update the variable.
In your second example you are reading the input field value inside the event handler, i.e. you are getting the current input value at the moment the handler is executed.
Assigning the new value
JavaScript is a pass by value language. That basically means that if you assign the value of a variable or an object property to another variable, a copy of the value is created and assigned. There is no intrinsic connection between the new variable and the "source variable". Thus assigning to title won't affect document.title in any way.
Here is a simplified example:
var foo = 42;
var bar = foo;
bar = 21;
console.log(foo); // still 42, assinging to 'bar' doesn't change 'foo'
Directly assigning to document.title, as in your second example, works as expected.
you are starting with JavaScript?
document.title is type string.
> typeof(document.title)
"string"
So when you assign title = document.title; in your first example, you actually copy the string value.
When you are declaring the title variable in the first try you just stored it's current value in the variable. In the second one you are directly setting document.title to another value. With that approach you don't need to pass the function the newTitle varaible since you aren't using it anyways. Try:
function titleChange() {
document.title = document.getElementById("newTitle").value;
}
I think it can be about parameter. You gave newTitle parameter to your function when you defined it but you didn't use it while calling your function. You can try this code
function titleChange() {
var title, newTitle;
title = document.title;
newTitle = document.getElementById("newTitle").value;
title = newTitle;
}
I am generating some JS variables on a Twig template and I am prefixing them with a dynamic value. For example:
<script type="text/javascript">
quoteGridId = 'grid_quote';
</script>
<script type="text/javascript">
quoteContactGridId = 'grid_quote_contact';
</script>
<script type="text/javascript">
archiveGridId = 'grid_archive';
</script>
I need to be able to use them in a Javascript file included after the page loads. How can I create an array of values containing all the *GridId vars?
I would like to be able to use the following on the script:
[
'quoteGridId' => 'grid_quote',
'quoteContactGridId' => 'grid_quote_contact',
'archiveGridId' => 'grid_archive',
]
UPDATE:
Let's try to get my problem clear for those ones opened to help. Currently I am working on a legacy system. Such system had a grid generating a gridId value and at the end a JS file was included and such file was using the var gridId to perform several things.
Now I need to replicate more than one grid on the same page and that becomes a problem since two grids are generating the same var name:
gridId = 'something';
gridId = 'something1';
When the script try to reach the gridId var is getting always the latest one (something1) and therefore no actions are being taken on the first grid.
My solution was to prefix the name to each gridId resulting on what I've as OP. Ex:
somethingGridId = 'something';
something1GridId = 'something1';
What I am trying to find is a way to re-use the main JS file by passing those dynamic gridIds but I can't find a way to get this to work.
The only solution I've in mind is to create the same file per grid and then change the value of gridId to the name of the ID to be used ....
I am open to ideas, any?
You can search the window variables with regex expressions (regular expression expressions?) i.e./.+GridId/ matches any word or variable that ends in GridId you can then iterate over them as you wish.
Example:
var pattern = /.+GridId/;
GridIds = []
for (var varName in window) {
if (pattern.test(varName)) {
GridIds.push({varName:window[varName]})
}
}
console.log(GridIds);
<script type="text/javascript">
quoteGridId = 'grid_quote';
</script>
<script type="text/javascript">
quoteContactGridId = 'grid_quote_contact';
</script>
<script type="text/javascript">
archiveGridId = 'grid_archive';
</script>
Hope this helps!
Instead of assigning quoteGridId = 'grid_quote', why don't you create a top level object and then assigning each var as a key-val pair, like:
var gridData = {}
gridData.quoteGridId = 'grid_quote'
gridData.quoteContactGridId = 'grid_quote_contact';
/* etc assignments */
//Access your data points like so in a loop, if you choose
Object.keys(gridData).forEach(key => {
const val = gridData[key]
//User `key`, and `val` however you'd like
})
i think you have you use List.
each time you push you value to the list like that :
var myList = [];
myList.push('something');
myList.push('something1');
now you cann access to all of them like that :
console.log(myList[0]);
console.log(myList[1]);
or just last :
console.log(myList[myList.length - 1])
This Code works to Give me stored cars Name
<html>
<head>
<script type="text/javascript">
var carArray=[];
function addToListCarArray(){
var newCarName=document.getElementById('carName');
carArray.push(newCarName.value);
if(window.localStorage){
localStorage.setItem("carNameKey",JSON.stringify(carArray));
}
}
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
for (i=0;i<carNames.length;i++){
alert(carNames[i]);
}
}
}
</script>
<title>Local Storage Demo</title>
</head>
<body>
<h1>Demo of Local Strorage</h1>
<div>
<input type="text" id="carName" name="carName"> </input>
<button onclick="addToListCarArray()">Add Car</button>
<button onclick="readCarNames()">Display</button>
<p id="displayCarNames"></p>
</div>
</body>
</html>
But how can i get the stored car names in form of an array and display it. I tried modifying the readCarNames() function in two ways but none of them worked.
I searched but everywhere it's all about passing the object and storing which i'm able to do but not able to retrieve it in form of an array and then print it
here is what i tried to work out but didn't worked (Edit: didn't worked out because of my Wrong Style of coding unfortunately)
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
var resultCarNames[]=JSON.parse(carNames);
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
and the second one that i attempted but didn't worked .
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
var resultCarNames[];
for (i=0;i<carNames.length;i++){
resultCarNames.push(carNames[i]);
}
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
EDIT: As pointed out the mistake i made by the veproza in Answer I was able to solve this ..
Here is the working snippet
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
var resultCarNames=JSON.parse(carNames);
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
}
In your first snippet, you seem to have it working correctly. By the line
carNames = JSON.parse(carNames);
you have the array of strings in carNames variable. After all, you iterate on it in the following for loop. You can try it by adding a line printing it, e.g.
alert(carNames);
If you want to print it to an element, you may want something like this:
document.getElementById('displayCarNames').innerHTML = carNames;
So your basic print array variable to an element would look like this:
function readCarNames(){
var storedString = localStorage.getItem("carNameKey");
var parsedArray = JSON.parse(storedString);
alert(parsedArray);
document.getElementById('displayCarNames').innerHTML = parsedArray;
}
Now, why it doesn't work in your code: In your second and third snippets, you need to know that in JavaScript, you don't initialize an array variable with var arr[]. You just say var arr = [] or var arr = JSON.parse(string). So this
var resultCarNames[]=JSON.parse(carNames);
should actually be just
var resultCarNames=JSON.parse(carNames);
and then it'll work.
Also note that variable.toString() returns a new variable, but does not change the original variable. Example:
var a = [1, 2, 3];
var b = a.toString();
console.log(a); // [1, 2, 3] - an array
console.log(b); // "1,2,3" - a string
So in your code, the line resultCarNames.toString(); doesn't do anything at all. Still, when assigning a variable to a DOM node via .innerHTML, it gets converted to String automatically.
The third snippet contains the same mistake with improper initialization. This time, the line var resultCarNames[]; should be var resultCarNames = [];. Other than that, you have a bit of a mess with curly braces, as you're missing the one closing the for cycle.
i am using Javascript on my page.
there is a problem when i use variable to send parameter to function,
when i write complete parameters directly as argument it works good like here
<script type="text/JavaScript">
var X = new MediaController({ContainerDiv:"player",MediaUrl:"test.flv"}');
</script>
but as i use a temp to put this argument in it, and then use temp as argument function it does not work!
<script type="text/JavaScript">
var temp;
temp = '{ContainerDiv:"player",MediaUrl:"test.flv"}';
var X = new MediaController(temp);
</script>
is there a point i missed?
You are assigning a String to the temp variable, which isn't the same as assigning the corresponding object. Instead of this
temp = '{ContainerDiv:"player",MediaUrl:"test.flv"}';
just do this:
temp = {ContainerDiv:"player",MediaUrl:"test.flv"};
and it should work the same.
You are passing in a string, not an object.
var temp = {ContainerDiv: "player", MediaUrl: "test.flv"};
var X = new MediaController(temp);
I need to dynamically assign the name of a function to an element of an associative array. This is my attempt which does not work. The problem I am asking for help with is here where I try to call the function: cr['cmd1'](x);
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var cr =[];
var x = 5;
cr['cmd1'] ='foo';
var msg = cr['cmd1'](x);
alert(msg);
function foo(y){
return y;
}
</script>
</head>
<body>
</body>
</html>
Edit: I being passed a string here cr['cmd1'] ='foo'; that I cannot control. That is why I have to work with a string as a starting point from an external application.
Access the functions using this syntax window[function_name]('para1');
Your usage will be something like this
var msg = window[cr['cmd1']](x);
If you want to store it as a function, pass the function directly. Otherwise, if you just want to store it as a string, then you can use the quotes.
Change:
cr['cmd1'] ='foo';
To:
cr['cmd1'] = foo;
I would use window[] and make sure its a function before trying to execute it since you don't have control over what is passed.
var f = window[cr['cmd1']];
if(typeof f==='function') {
f(x);
}
What you are doing there is assigning a function to an array. A more common pattern that you are probably trying to do is to call a function on an object with the array notation.
<script type="text/javascript">
var cr = {};
cr.cmd1 = function foo(y){
return y;
};
var x = 5;
var msg = cr['cmd1'](x);
alert(msg);
</script>
This code results in an alert box that contains the number 5.