set global var using jquery and dynamic variable name - javascript

I am trying to set a javascript global var using jquery and dynamic variable names like this:
var home_phone_number // located outside of any functions
.
.
.
function setPhoneVars(phone){
// do stuff here to determine the correct prefix
thePrefix = 'home_phone_'
$(thePrefix + "number").val(phone.number);
}
When I do this, the value of home_phone_number is undefined.
But, when I set the phone number manually, like this:
home_phone_number = phone.number
the variable is set as expected.

Global variables are properties of the window object, so can be accessed as such:
window[thePrefix+'number'] = phone.number;

You can access global variables through window object, e.g.
var home_phone_number = "value";
function setPhoneVars(phone) {
var thePrefix = "home_phone_";
window[thePrefix + "number"] = phone.number;
}

Instead of having such many globals.. you can use a single object..
var globals = {
home_phone_number: 0 // located outside of any functions
}
function setPhoneVars(phone){
// do stuff here to determine the correct prefix
thePrefix = 'home_phone_'
globals[thePrefix + "number"] = phone.number;
}

I think your use of JQuery is not appropriate; .val() is intended to set the value of HTML elements, i.e. HTML objects in the DOM.
To simply set a dynamic JavaScript variable you could use eval() which is a JavaScript function which treats a string as executable code;
thePrefix = "home_phone_";
eval(thePrefix + "number = phone.number;");

Related

How can I get the content of a variable that I don't know its name

Although this question is about datatables, it's not specifically about it.
I have datatables init stored in variables. The variable name varies as I have several datatables on the page. I am trying to collect the content of those variable by assembling the variable's name and I don't know how i can later use the 'string' I've assembled as a variable
For example:
var var_1_id_0 = $('.item1').datatable();
var var_1_id_1 = $('.item2').datatable();
var var_1_id_2 = $('.item3').datatable();
// later in the code.
var varname = 'var_1_id'+'_0';
// varname now holds the string 'var_1_id_0' which is the first variable.
My question is how can I use varname's string 'var_1_id_0' as the variable 'var_1_id_0'?
I hope that make sense.
Thanks
It is not possible. The closer solution is this one:
var datatable={};//A new Object.Arrays doesn't work property for this.
datatable['var_1_id_0'] = $('.item1').datatable();
datatable['var_1_id_1'] = $('.item2').datatable();
datatable['var_1_id_2'] = $('.item3').datatable();
// later in the code.
var varname = 'var_1_id'+'_0';
console.log(datatable[varname]);
Try it like this:
var varname = 'var_1_id'+'_0';
alert(window[varname]);

How to call ID through local Variable

if am having html
<TableView id=img1></TableView>
<TableView id=img2></TableView>
normally
$.img1.backgroundImage = "/Picture1.jpeg"
but I want to know how to store the id in local variable and call the same function, in place of img1 I have to use local variable. is any possibility of this.
Normally $.img1.backgroundImage = "/Picture1.jpeg" would be nonsense since jQuery doesn't populate itself with properties referencing all elements with ids on a page.
Converting that to use a variable instead of an identifier (let's say var foo = 'img1'; for the benefit of all the following examples) would be
$[foo].backgroundImage = "/Picture1.jpeg";
(That's equivalent to the original code, but since I wouldn't expect the original to work, this won't either).
To actually set the backgroundImage property in JS you would:
document.getElementById(foo).style.backgroundImage = "url(/Picture1.jpeg)";
or if you are being a jQuery junkie:
jQuery('#' + foo).css('background-image', 'url(/Picture1.jpeg)');
Yes Sure but need to adjust the code accordingly to set the background image
var img1 = $("#img1")
img1.css("background-image","/Picture1.jpeg");
var images = $("#img1");
or also you can use
var images_obj=form_name.element_name;
var yourVar= $("#img1").attr("id");
I think you want to change the background image css property of an element selected by id, who is in a local variable?
var yourid = "img1";
$('#' + yourid ).css('background-image', '/Picture1.jpeg');
You better save the object instead of id as you would need to get element by id again and again.
var img1Obj1 = $('#img1'); //jQuery object
var img1Obj2 = $('#img1')[0]; // DOM javascript object

javascript eval - how to assign value to object property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic object property name
I have an object like this
var localAppConfig = {
wallet:0,
paySomeone:0,
payBills:0,
accounts:0,
moveMoney:0,
alerts:0,
offers:0,
checkIn:0
};
I want to set value 1 for particular elements within this localAppConfig
Which element needs to be set is retrieved from the json - which arrives from the server.
say, I want to set value = 1 for wallet, paySomeone, payBills, alerts, offers, checkIn
These are retirved from the json like
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = eval('localAppConfig.'+name);
eval('localAppConfig.'+name)=1;
}
var name contains name of the element and I am able to access its value correctly,
How can I set the value using javascript?
I tried accessor=1 but its not working.
Thanks :)
Anyhow: try this on for size:
localAppConfig[name] = 1;//where name is a variable of choice, it's value will be used as the propertyname
And again:
-When all you have is the eval hammer, everything looks like your thumb.
–Brendan Eich in response to: we should encourage use of eval() rather than the Function constructor for dynamic creation of functions.
But why use a list of the properties? you might as well use a for...in loop: in case of objects, like yours, it's perfectly all right. As long as you check .hasOwnProperty, too:
for (var prop in localAppConfig)
{
if (localAppConfig.hasOwnProperty(name))
{
//set, delete... do whatever
}
}
You should do this instead:
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
Try localAppConfig[name] = 1;
It's just a javascript object, no need to use eval() on it.
Don't use eval(). You can add a property by referencing the index of that value within your object. If it doesn't exist then it will be created, otherwise the value will be overridden.
Try the following instead:
// localAppConfig[list[i].handle] = 1;
for(var i=0;i<len;i++){
localAppConfig[list[i].handle] = 1;
}
Or if you intend to reference the variable in another place then set a variable with the value of list[i].handle:
for(var i=0;i<len;i++){
var name = list[i].handle;
var accessor = localAppConfig[name];
localAppConfig[name] = 1;
}

jQuery: substitute (concatenated) button value with variable string

So, I have a button whose value is concatenated from variables and strings:
$('#btn1').attr('value','question'+currid+'ans1').button('refresh');
This will return something like question5ans1, for example. Now, at the top of the javascript document, this value exists as a variable with a string associated, like this:
var question5ans1 = "Sydney";
The problem is that the button displays "question5ans1" instead of "Sydney". Is there any way to fix/change that?
Use eval to evaluate the string as var.
$('#btn1').attr('value', eval('question'+currid+'ans1')).button('refresh');
Instead of eval, a better solution is to have such var in a object like below,
var questions = {'question5ans1' : 'Sydney' };
and in the function,
$('#btn1').attr('value', questions['question'+currid+'ans1']).button('refresh');
If the variable is in the global scope, you can probably fetch it like this:
$("#btn1").val(window['question' + currid + 'ans1']);
You should attach these kinds of variables to an object as you cannot directly convert a string to a variable name. eval should not need to be used.
var q = {
question3ans1: "London",
question4ans1: "Tokyo",
question5ans1: "Sydney"
};
$('#btn1').attr('value', q['question' + currid + 'ans1'] ).button('refresh');

Javascript: give a variable a name made of 2 variables

I want to create a new variable in javascript but it's name should made of a stale part and a variable one like this:
tab_counter = 1;
var editor + tab_counter = blabla
well i want the new variable name to be in this case editor1, is this possible?
You cannot create a stand-alone variable name that way (except as a global) (edit or except with eval()), but you can create an object property:
var tab_counter = 1;
var someObject = {};
someObject['editor' + tab_counter] = "bla bla";
You can create globals as "window" properties like that, but you probably shouldn't because global variables make kittens cry.
(Now, if you're really just indexing by an increasing counter, you might consider just using an array.)
edit also see #Birey's somewhat disturbing but completely correct observation that you can use "eval()" to do what you want.
It is possible
var tab_counter=1;
eval("var editor"+tab_counter+"='blah'")
alert(editor1);
eval("var editor"+tab_counter+1+";")
editor2='blahblah';
alert(editor2);
http://jsfiddle.net/5ZLYe/
You can do the eval method used by Birey or you can create a custom property of an object such as...
obj[editor + tab_counter] = blabla;
But it sounds like you're going about doing whatever you're doing in a particularly horrible way. If you just want to store multiple items which you can index into use an array...
var array = [];
array[0] = blabla;
array[1] = blabla2;
alert(array[0]); //shows value of blabla
alert(array[1]); //shows value of blabla2
It seems like you may want to consider using a Dictionary for something like this. This link which references this link describes your options there.

Categories

Resources