"Can you please provide instructions on how to retrieve images from an array and insert

I have a dropdown list with animal options:

<select id="animal">
<option>Choose an animal </option>
<option value="1">animal 1 </option>
<option value="2">animal 2</option>
<option value="3">animal 3 </option>
</select>

Furthermore, I have a 2-dimensional array containing image sources:

var pictureList = [
    ["images/img1.jpg","images/img2.jpg"],
    ["images/img3.jpg","images/img4.jpg", "images/img5.jpg"],
    ["images/img6.jpg"]
];

I need help creating a script to extract images from the array and combine them into a single image list. For example, if I select "animal 1," I want the following output:

 <ul id="slider"> 
  <li><img class="imageClass" src="images/img1.jpg"/></li>
  <li><img class="imageClass" src="images/img2.jpg"/></li>       
 <ul>

For "animal 2":

  <ul id="slider"> 
   <li><img class="imageClass" src="images/img3.jpg"/></li>
   <li><img class="imageClass" src="images/img4.jpg"/></li> 
   <li><img class="imageClass" src="images/img5.jpg"/></li>      
  <ul>

Answer №1

To put your request in different words:

You will have to choose a single animal and display a list of images related to that specific animal on the screen.

Simply retrieve the selected animal's value, find its corresponding position in the array, and utilize that array to showcase the HTML content. Check out this plunkr I created for you: Link here:

$('#animal').change(function () {
    var animalImages = pictureList[$(this).val() - 1];

    $('#slider').html('');
    for (var i = 0; i < animalImages.length; i++) {
      $('#slider').append('<li><img class="imageClass" src="' + animalImages[i] + '" /></li>');
    }
});

I haven't tested the implementation yet.

Answer №2

To iterate over your 2D array, you will need to use a loop like the following:

for(var x = 0; x < imageArray.length; x++) {
    var row = imageArray[x];
    for(var y = 0; y < row.length; y++) {
        alert("imageArray[" + x + "][" + y + "] = " + row[y]);
    }
}

In your select box, set an onChange event to call a method that takes the selected option value as a parameter. By making some slight adjustments to the above loop code, you can easily retrieve the nth element from the array.

You can then create a function to dynamically generate img tags with src attributes based on the values in the imageArray.

Answer №3

Take a look at this essential javascript snippet, All that's required is jquery

for (var i = 0; i < pictureList[$( "#animal" ).val()].length; i++) {
  $("#slider").append('<li><img class="imageClass" src="'+pictureList[$( "#animal" ).val()][i]+'"/></li>')
}

Answer №4

Here is a sample code snippet for changing the animal displayed:

function updateAnimal(val){
    var slider = document.getElementById('slider');
    
    if(val !== ''){
        slider.innerHTML = '';

        for(var i = 0; i < pictureList[val-1].length; i++){
            var li = document.createElement('li');
            var img = document.createElement('img');

            img.src = pictureList[val-1][i];
            li.appendChild(img);

            slider.appendChild(li);
        }
    }  
}  

Check out this JSFiddle example for reference.

Answer №5

Here is a JSFiddle I put together for you click here.

Javascript

var imageGallery = [
    ["pictures/pic1.jpg","pictures/pic2.jpg"],
    ["pictures/pic3.jpg","pictures/pic4.jpg", "pictures/pic5.jpg"],
    ["pictures/pic6.jpg"]
];

var element = document.getElementById("animal");
element.onchange = function(){
    var slideShow = document.getElementById("slideshow");
    slideShow.innerHTML = "";
    var value = element.options[element.selectedIndex].value;
    for (var index in imageGallery[value-1]){
        var newSlide = '<li><img class="imageClass" src="'+(imageGallery[value-1][index])+'"/></li>';
        slideShow.innerHTML += newSlide;
    }
};

HTML

<select id="animal">
    <option>Select an animal</option>
    <option value="1">Animal 1</option>
    <option value="2">Animal 2</option>
    <option value="3">Animal 3</option>
</select>

<ul id="slideshow"></ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in NodeJS session: the variable "request" is not defined

Recently, I have started working with NodeJS and I am currently facing an issue while trying to implement sessions in my project. Any assistance or guidance on this matter would be greatly appreciated. Below is the code snippet where the error occurs: va ...

I am encountering an issue where my JavaScript code is not being executed on my HTML page as expected. I

I have implemented an accordion using Bootstrap 4 accordion, card, and collapse classes in my HTML page with success. However, I am facing a challenge with maintaining the state of the accordion when navigating away from and then returning to the page. By ...

Set object keys dynamically using jQuery or pure JavaScript

I am facing an issue with populating data into an empty object dynamically Desired outcome userData = { programmer: "Jeff", designer: "Obama', CEO: "Elon Musk" } My current approach. var userData = {}; var allData = []; ...

Adding Elements to an Array Using a Form

Only the editor has permission to post data into the database, while the price cannot be posted into the database. How can I create a query where the first row in a form includes fields for Fullname and Age, and additional rows can be added with the same ...

Adding up column values in AngularJS arrays

I am completely new to AngularJS (and coding in general). I'm currently working on a simple game project and have hit a roadblock. Essentially, users can input words into a list and my script assigns 5 random numbers (within a specified range) to eac ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server. Instead of using PDFJS.getDocument('helloworld.pdf') I prefer to display the downloaded PDF in the browser through a ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

Activate the drop-down menu in Angular 6 by hovering over it with your mouse

I am just beginning my journey with Angular 6 and Bootstrap. Currently, I am working on a Navigation bar that consists of 3 navigation items. One of the nav items is called "Store", and when a user hovers their mouse over it, I want to display a mega menu ...

Is there a way to prevent pop-up windows from appearing when I click the arrow?

Is there a way to display a pop-up window when the green arrow is clicked and then hide it when the arrow is clicked again? I tried using the code below but the pop-up window disappears suddenly. How can I fix this issue using JavaScript only, without jQue ...

"jQuery's toggleClass Method for Efficient Class Swapping

I have been working on a script that is supposed to change the color of a square upon clicking it using the toggleClass() method in jQuery. However, my code seems correct but for some reason, the square's color isn't changing. Can someone help me ...

Express (MEAN stack) does not update page URL when using res.location

I am in need of a hard-coded, password-protected page. I have used href for redirection to a page located at /admin/user/password: <a ng-href="/admin/{{user}}/{{password}}" class="form-control btn btn-primary" >Submit</a> In my code, I am ...

To iterate through a multi-dimensional array

I am facing an issue with fetching data within an array in the code below var str = "Service1|USER_ID, Service1|PASSWORD" var str_array = str.split(','); console.log(str_array) for(var i = 0; i < str_array.length; i++) { str_array[i] = st ...

"Can you tell me more about the purpose of $cacheFactory

I am struggling to find information on the purpose and functionality of $cacheFactory in application development. According to the Angular Documentation, "Factory that constructs cache objects and gives access to them." -- $cacheFactory However, this e ...

How do you include attachments in the body of form data using C# in a REST API?

Seeking help with uploading files to Azure Blob using Postman Rest API calls. I need guidance on attaching files to form data body through C# code in the frontend, and ideally receiving a result containing an ID and File Type information. ...

Transferring data between AngularJS services situated on separate pages

I'm currently working on an example project for AngularJS involving a simple book store. I am facing a challenge where I need to pass a book ID from a home page to a service on an edit page in order to render the book details. The issue I'm encou ...