Gaby
Gaby

Reputation: 85

Get array value from variable

I'd like to get the value of an array depending on the index of the ul element. I'll try to explain myself:

var descgal0 = ["3456", "463", "6557", "5242"];
var descgal1 = ["gfdgfd" "gfgdfg", "gfdg", "gfdg"];
$("#gal-content-all section ul li img").click(function() {
   var index = $(this).parent().index();
   var indexul = $(this).parent().parent().parent().index();
});

The problem is

$("#gal-zoom h4").text(descgal0[index]); //WORKS!
 $("#gal-zoom h4").text("descgal"+indexul+[index]); //DOESN'T WORK :(

How could I get the array[li] value depending the ul I'm clicking on...?? Thank you!!!!

Upvotes: 0

Views: 62

Answers (4)

dreamweiver
dreamweiver

Reputation: 6002

Try this way

$("#gal-zoom h4").text(descgal0[index]); 
 arrName="descgal"+indexul;
$("#gal-zoom h4").text(arrName[index]); 

Happy Coding:)

Upvotes: 0

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

you have to use eval, try this:

$("#gal-zoom h4").text(eval("descgal" + indexul + "[" + index + "]"));

instead of this:

$("#gal-zoom h4").text("descgal"+indexul+[index]);

Upvotes: 0

Florian F.
Florian F.

Reputation: 4700

Considering your data model eval seems like the only way :

$("#gal-zoom h4").text(descgal0[index]); //WORKS!
$("#gal-zoom h4").text(eval("descgal"+indexul+"["+ index + "]")); //SHOULD WORK :D

But, if you have control over the data model, you could go with something prettier than an eval, like this :

var descgal = [["3456", "463", "6557", "5242"],["gfdgfd" "gfgdfg", "gfdg", "gfdg"]];

$("#gal-zoom h4").text(descgal[indexul][index]);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can use array of arrays since you have sequential indexes

var descgals = [
    ["3456", "463", "6557", "5242"],
    ["gfdgfd", "gfgdfg", "gfdg", "gfdg"]
];
$("#gal-content-all section ul li img").click(function () {
    var index = $(this).parent().index();
    var indexul = $(this).parent().parent().parent().index();
    $("#gal-zoom h4").text(descgals[indexul][index]);
});

Upvotes: 1

Related Questions