user3723269
user3723269

Reputation: 19

jQuery ''mapping'': How to iterate through an array, using variable value

I am trying to map two data "points" together, which do not really have anything in common. I have an array which contains images at certain positions, within the array. I also have a variable that can contain various values (1, 2 or 3), and I want to map the array position (1, 2 or 3) and the variable value, to show the image that is in the specific array position.

<script>

var images = new Array()
images[1] = 'image/position/in/folder/image.jpg';
images[2] = 'image/position/in/folder/image.jpg';
images[3] = 'image/position/in/folder/image.jpg';

var var_name = somedata


/*----here I need help or guidance----

jQuery(document).ready(function() {
   var jQuerydiv = jQuery(".image_div");

   jQuery.each(images, function(i, val) {

      jQuery("<img />").attr("src", val).appendto(jQuerydiv);

   });
});


/*------guidance/help ENDS------------

<script>

<div class="image_div"></div>

This script throws all images in the array "images" to div "image_div". I want to only show the image in the array, which position (1, 2 or 3), matches the value of variable var_name, which can contain 1, 2 or 3.

Anything obliged.

Upvotes: 1

Views: 110

Answers (2)

Devram Kandhare
Devram Kandhare

Reputation: 781

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script> 
    var images = new Array() 
    images[1] = 'image1.png';
    images[2] = 'image2.png';
    images[3] = 'image3.png';

    // console.log(images);
    // [empty × 1, "image1.png", "image2.png", "image3.png"]
    // here images are put at index 1,2,3
    var var_name = 1;

    $(document).ready(function() {
      var jQuerydiv = $(".image_div");

    $.each(images, function(i, val) {
    // now append image at index 1 to div
    if(i == var_name){
        $("<img />").attr("src", val).appendTo(jQuerydiv);
    }
   });
});
</script>

<div class="image_div"></div>

Upvotes: 1

bhansa
bhansa

Reputation: 7504

Use appendTo and access the images array from 0. Also close script tag

img
{
border: 1px solid #000;
  width: 50px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

var images = new Array()
images[0] = 'image/position/in/folder/image.jpg';
images[1] = 'image/position/in/folder/image.jpg';
images[2] = 'image/position/in/folder/image.jpg';


jQuery(document).ready(function() {
   var jQuerydiv = jQuery(".image_div");

   jQuery.each(images, function(i, val) {

      jQuery("<img />").attr("src", val).appendTo(jQuerydiv);

   });
});

</script>

<div class="image_div"></div>

Upvotes: 0

Related Questions