jQuery: substitute (concatenated) button value with variable string
-
28-04-2021 - |
Question
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?
Solution
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');
OTHER TIPS
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');