Variable variables in javascript
Posted: Mon Jan 12, 2009 8:18 am
Came across a problem I've never had to solve before, namely the title of this post. I have a page that is mostly dot net (vb) and in it I'm using a javascript framework to do some nice menu animations and what not, mostly it's just a window that responds when a radio button is pressed. Now the problem is, t he number of radio buttons is dynamic, or rather, should be dynamic based on a parameter vb has. I have no problems getting said parameter into javascript (I can alert it, for example), but what I want to do isn't working.
I want to create a loop that creates a variable for the number of something selected on a previous page. So if the parameter in vb comes in as 5, I should have 5 variables. I'm essentially writing code that should write code. I used a for loop and eval but no dice. YES I know eval is awful and evil, but the other methods I googled including dot notation and square brackets do not work. Here was my idea that does not work to demonstrate the effect I want:
So let's say my initial variable numProps = 5, I should get the variables prop1, prop2, prop3, prop4, prop5 all with a value of "testing".
I want to create a loop that creates a variable for the number of something selected on a previous page. So if the parameter in vb comes in as 5, I should have 5 variables. I'm essentially writing code that should write code. I used a for loop and eval but no dice. YES I know eval is awful and evil, but the other methods I googled including dot notation and square brackets do not work. Here was my idea that does not work to demonstrate the effect I want:
Code: Select all
<script language="javascript" type="text/javascript">
var numProps = <%=numProps%>;
for(i=1;i<numProps+1;i++){
eval("prop" + i) = "testing";
alert(prop1)
}
So let's say my initial variable numProps = 5, I should get the variables prop1, prop2, prop3, prop4, prop5 all with a value of "testing".