Convert string to variable name in JavaScript
If it's a global variable then window[variableName]
or in your case window["onlyVideo"]
should do the trick.
Variable name as a string in Javascript
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
Set string to variable name
You can store the data in an object with the keys matching your select's values.
var data = {
basketball: "changeable-string",
handball: 760,
football: null,
baseball: "description: ball-game to play"
}
function myFunction(el) {
console.log(data[el.value])
}
<select name="box" onchange="myFunction(this);">
<option value="football">Football</option>
<option value="handball">Handball</option>
<option value="basketball">Basketball</option>
<option value="baseball">Baseball</option>
</select>
JavaScript convert a string to a variable name?
The eval
way:
Not sure what are you doing and I hope you're aware of the bad sides of eval
, but that's the only way you can turn this code into a working code:
var metFital = { "IMP_TRAV_SP": { type: "cont", Est: 0.055 }}
var IMP_TRAV_SP= 20;
var EvalueFital=0
for (var par in metFital) {
if (metFital[par].type == "cont") {
EvalueFital = EvalueFital + ((metFital[par].Est) * eval(par));
}
};
alert(EvalueFital);
Convert string to variable name to use in jQuery .animate
you can use window object to access global variables
var nextVar = window['nav'+nextLoc];
How to use a string as a variable name in Javascript?
Stop. Reorganise your code. If you want to select variables with a variable, then there has to be a logical grouping for them. Make it explicit.
var chat = {
"1": "one",
"2": "two"
};
var id = 1;
var new_is_a_keyword_and_cant_be_an_identifier = chat[id];
Related Topics
How to Remove Item from Array by Value
Evaluating a String as a Mathematical Expression in JavaScript
How to Post a File from a Form With Axios
Check Browser CSS Property Support with JavaScript
How to Dynamically Modify <Select> in Materialize CSS Framework
Using Jquery to Know When @Font-Face Fonts Are Loaded
Dynamically Expand Height of Input Type "Text" Based on Number of Characters Typed into Field
Nodejs and Socket.Io, Is It Pure JavaScript
Dynamically Load a JavaScript File
How to Set a Cookie for Another Domain
How to Determine If a Variable Is 'Undefined' or 'Null'
Iterating Over Result of Getelementsbyclassname Using Array.Foreach
CSS Transitions Do Not Work When Assigned Trough JavaScript
Access CSS File Contents via JavaScript
Event Listener on a CSS Pseudo-Element, Such as ::After and ::Before