Jump to content

dinamic variable mane


netcracker

Recommended Posts

how do i create a dinamically named variable and asign a value to it?take for instance the following function:

<script type="text/javascript">function go2page(variabila, valoarea) {	var variabile_bloc = "www";	var variabile_scara = "ssss";	eval("variabile_"+variabila = valoarea);	var pagina = "imobile_search.php?bloc="+ variabile_bloc;	document.location=pagina;}</script>

and this element:

<select name="bloc" id="bloc" onchange="go2page('bloc', this.options[this.selectedIndex].value);">	<option value="1">bloc 1</option>	<option value="2">bloc 2</option>	<option value="3">bloc 3</option></select>

the select should asign the variable variabile_bloc" the value this.options[this.selectedIndex].value.any ideeas, please?

Link to comment
Share on other sites

YES! that isi it: :)

eval("variabile_"+variabila + " = valoarea");

I was close, but note close enough: :mellow:

eval("variabile_"+variabila = valoarea);

thank you! :)

Link to comment
Share on other sites

For better efficiency, I believe (though I haven't really tested) that you can use an associative-array-like notation to get a variable name dynamically, since variables are also properties.i.e. something like

window["variabile_"+variabila] = valoarea;

This works best if you use a custom object of yours that would store all data. eg. if you had an object like:

var variables = {"a" = "value of a", "b" = "value of b"};

you might as well use

variables["a"]

later on, where the "a" can be fetched with a variable, like

variable[valoarea]

Link to comment
Share on other sites

the array-method would have been my final approach, but i didn't want to go there, for fear i should complicate thing unnecessarilly.eval("variabile_"+variabila + " = valoarea") works best, and it is simplier.

Link to comment
Share on other sites

the array-method would have been my final approach, but i didn't want to go there, for fear i should complicate thing unnecessarilly.eval("variabile_"+variabila + " = valoarea") works best, and it is simplier.
But it's less efficient! A LOT less efficient. It makes your whole script run slower. If you run this eval() statement a lot, you'll eventually see your script hanging. And with the array-like-method (I'm emphasizing "like", because technically speaking, it's an object, not an array, and there are differences between the two), it's a lot faster. Don't believe me? See Opera's efficient JavaScript article.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...