Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$$var (in php) Equivalent in javascript

I have a variable var commision_1 = 2000 ;var commision_2 = 4000; and a function:

function updateCommission(period){
    $("input:text[name='commission']").val('commision_'+period);
}

I would like if period is 1 then the value of the textbox be 2000; I know I can use arrays, but I am working on someone else's code, is there a way around it just like in php how I would have written $x = 'commision_' .$period; echo $$x;

like image 590
Njuguna Mureithi Avatar asked Jun 25 '26 19:06

Njuguna Mureithi


1 Answers

You can use square bracket notation to get variable variables.

Provided these variables are defined in the window scope:

function updateCommission(period){
    $("input:text[name='commission']").val(window['commision_' + period]);
}

Having said that, defining numbered variables (all the way up to 2000..!?) isn't a good idea. An array was born to serve this purpose. My best answer would be to request these variables be re-written as an array, but I appreciate this is often easier said than done.

like image 168
George Avatar answered Jun 28 '26 11:06

George