Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ID to call a variable in jQuery

I have about 40 swatches each with an id. Upon clicking the swatch an image below should change and the text within the image will change as well. Currently I'm grabbing the id and using that to add to the URL of the image like so:

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId');
  })

Thant works great!

Also, inside my script I have all of the text saved as variables, like so:

var firstText = "Text for the first image",
    secondText = "Some other kind of text",
    thirdText = "Yet more text that's really different from the other two";

The id matches the variable when "Text" is added to it, so I assumed I could just do something like:

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");
    var newText = clickedId + "Text"

    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId);
    $('#imageText').html(newText);

  })

I assumed, in this case, "newText" would refer to the global variables ("firstText", "secondText", "thirdText", etc.). But, no dice.

Is there a way I can make the ID refer to the global variable to change the text? At one point I also tried turning the new text variable ("newText") into a string, but that didn't work either.

like image 800
James Conroy Avatar asked Jan 23 '26 16:01

James Conroy


1 Answers

A cleaner, more readable solution would be to use a javascript object, like so:

var imageTexts = {};
imageTexts['first'] = "Text for the first image";
imageTexts['second'] = "Some other kind of text";
imageTexts['third'] = "Yet more text that's really different from the other two";

Then, in your jQuery, modify the line as follows:

$('.swatches').children('img').click(function(){
    var clickedId = $(this).attr("id");
    $('#wallPic').attr('src', '//somepathtogettothisimage/theproductname_' + clickedId);
    // Reference "imageTexts" with the clickedID (assuming 'first', 'second', etc)
    $('#imageText').html(imageTexts[clickedId]);

  })
like image 178
random_user_name Avatar answered Jan 25 '26 05:01

random_user_name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!