-4

I got the follow code:

var image1 = 'aaa.jpg';
var image2 = 'bbb.jpg';
var image3 = 'ccc.jpg';
var image4 = 'ddd.jpg'; // all dynmically created

current = 1; // dynamically changing value, in this case between 1 and 4

What I need now is to alert alert(image1); but on this way: alert(image + current);

Is it even possible this way? I hope I explained clearly what I need.

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
donbingo
  • 29
  • 5
  • Thats a nice solution too Jack, not easy to create with PHP but would work :D – donbingo Jul 09 '15 at 22:32
  • How do you create the variables using PHP currently? Seems a bit like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – insertusernamehere Jul 09 '15 at 22:34
  • Like that: – donbingo Jul 09 '15 at 22:37

5 Answers5

1

Do it this way:

this.image1 = "aaa.jpg";

alert(this["image" + "1"]);
Joerg
  • 3,102
  • 2
  • 24
  • 30
0

From what I see, I think you've on the right path. But here are some things to consider...

  1. Put the dynamically created variable in quotes to make them a string:

var image1 = 'aaa.jpg';

  1. When you out put in the alert box put the word 'image' in quotes also. That way it will be a string too:

alert(eval('image'+current));

  1. The alert box won't actually show the image. It will only show the name of the image that is stored in the variable. I think this is what you're going for.

Good Luck!

I see you edited the question to put it the dynamic variable in quotes. Well done.

Miles
  • 764
  • 2
  • 11
  • 20
0

I solved it the way one user posted it and deleted his answer (why?):

alert(eval('image'+current));
vaultah
  • 44,105
  • 12
  • 114
  • 143
donbingo
  • 29
  • 5
0

As it was suggested in the comments and based on your PHP code from the comments: Create a JavaScript array to store your data instead of creating lots of variables. You can accomplish it for example like this:

Create string containing all images

<?php
    $images = '';
    while($row = mysqli_fetch_assoc($result)) {
        $images .= ( $images ? ',' : '' ) . '"' . $row['image'] . '"';
    }
?>

Output

var images = [<?php print $images; ?>];
alert (images[0]);
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
0

You're clearly working with a collection, so you should create an array structure in this case:

<?php 

$images = [];
while ($row = mysqli_fetch_assoc($ergebnis)) {
    $images[] = $row['image'];
}

?>
<script type="text/javascript">
var images = <?php echo json_encode($images) ?>;
</script>

You can then reference each image path via, e.g. images[0].

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309