jQuery: substitute (concatenated) button value with variable string - javascript

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

Related

Unable to get value of JavaScript Object [duplicate]

I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.

set global var using jquery and dynamic variable name

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

Javascript Computed Values With Arrays

Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']

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.

How to directly access (javascript) split values?

Is there any way to access split values without putting them into separate value?
var content = "some|content|of";
var temp = content.split("|");
var iwilluseit = "something" + temp[1] + temp[2]
How to do this w/o temp variable ?? (inline in setting of iwilluseit var)
It's incredibly inefficient, but you could call split multiple times:
var iwilluseit = 'something' + content.split('|')[1] + content.split('|')[2];
There's also the slice() + join() option:
var iwilluseit = 'something' + content.split('|').slice(1,2).join('');
Really, though, just creating the temp variable is the best way to go.
content.split("|").slice(1,3).join("")
No, you need to assign the result of Array.split() to an intermediate variable before it can be used, unless you don't mind the performance hit of calling Array.split() for each value you want to grab.
You could patch String.protoype to add a method that would take an array of strings and substitute it into a string.
How about:
var iwilluseit = "something" + content.split("|").slice(1,3).join(""));
You can also do:
var iwilluseit = "something" + content.substr( content.indexOf( "|" ) ).split("|").join("");
Of course, this will only work if you are simply trying to remove the first value.
More importantly:
Why do you need it to be in line?
If the purpose of not assigning it to a variable is to be able to do this in a context
where you can only have one Javascript expression, you could also use a closure, and
assign it to the variable in it:
(function() { var temp = content.split("|"); return "something" + temp[1] + temp[2]; })()
Which would be usable in an expression context, and not have the performance hit.

Categories

Resources