JavaScript dynamic function name - javascript

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.

Related

unable to print result line by line

I am unable to print result in line by line,it's coming in one line ,how to solve this....
I tried this code-
<script>
function know(){
var num =Number(document.getElementById('number').value);
var range=Number(document.getElementById('range').value);
var output="";
var final=[];
for(i=1;i<=range;i++)
{output=i*num;
final.push(output)
final=final.replace(",","<br/>")}
document.getElementById('result').innerHTML=final
}
</script>
There is 2 issues in it:
the for loop i you need to declare as a var or let(I recommend let)
there is no replace method in array, you can use map in this case
So you can re write the method like this.
<script>
function know(){
var num =Number(document.getElementById('number').value);
var range=Number(document.getElementById('range').value);
var output="";
var final=[];
//for(i=1;i<=range;i++)
for(let i=1;i<=range;i++)
{output=i*num;
final.push(output)
//final=final.replace(",","<br/>")
}
final = final.map((d, ind) => d*(ind+1))
document.getElementById('result').innerHTML=final
}
</script>

javascript get value of a field in an HTML object

In console.log I have an HTML object like this...
If I wanted to make a javascript to access and display the value of "name" from the HTML object (not by another method) like so...
<script type="text/javascript">
var getName = how to get it?
console.log(getName);
</script>
... how would I do it?
What if "name" was nested in something like "attributes: NamedNodeMap"? How would I get a nested value?
Use dot "." to get to all values - so if it were
Object {
anotherObject:{
Name: value
}
}
You would use var getName = Object.anotherObject.name; to get the value.
And you would have to find out the names of your objects in order to Access them.
In your case the object seems to have an _id
attribute so you can find it through that perhaps:
<script type="text/javascript">
function FindByAttributeValue(attribute, value) {
var All = document.getElementsByTagName('*');
for (var i = 0; i < All.length; i++) {
if (All[i].getAttribute(attribute) == value) { return All[i]; }
}
}
var objectToFind = FindByAttributeValue("_id","zr9Gk...");//put in the ID here
var getName = objectToFind.name;
console.log(getName);
</script>
I got the function from here.
You have many ways:
if console log shows _id and name then.
use:
alert(object.name); // For testing purpose.
alert(object._id); // For testing purpose.
if it is a selector then use:
<script type="text/javascript">
var getName = $("selector").text();
console.log(getName);
</script>

Pass by reference to COM object in JavaScript

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);

How to Get back stored data in LocalStorage HTML 5 in form of array?

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 can not use variable as javascript argument

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);

Categories