Switching the image hosted on a local server when an option is selected from the dropdown menu

I am trying to create a functionality in my project where I have a select box and based on the option selected, I want to change the image displayed on the browser. However, I don't want to manually code all the images into my HTML file. Here is an example of what I currently have:

<select>
       <option>1</option>
       <option>2</option>
       <option>3</option>
</select>


<ul>
   <li id="myImg">    
       <img src="images/1.jpg">
   </li>
</ul>

While I have set up my HTML structure, I am unsure how to implement the JavaScript needed to achieve this dynamic image change feature. My goal is to be able to select an option from the dropdown menu, have the corresponding image from my local system replace the current one being displayed. Is this feasible or am I asking an impractical question? I would greatly appreciate any assistance with this issue as it is important for my project. Thank you.

Answer №1

Here is an example of using HTML and JavaScript together:

<select id="mySelect">
   <option>Option 1</option>
   <option>Option 2</option>
   <option>Option 3</option>
</select>

When a selection is made in the dropdown, the following JavaScript code will change the source attribute of an image based on the selected value:

document.getElementById('mySelect').onchange = function(){
  document.querySelectorAll('#imageContainer img')[0].src = '/pictures/' + this.value + '.jpg';
};

Answer №2

<select name="choose_image" id="choose_image" onchange="swapImage(this);">
    <option value="https://www.pexels.com/photos/4141719/pexels-photo-4141719.jpeg">Nature</option>
    <option value="https://www.pexels.com/photo/underwater-world-simulated-with-fish-models-and-corals-1789222/">Underwater</option>
    <option   alue="https://www.pexels.com/photo/beautiful-waves-hitting-the-shore-1935521/">Beach</option>
</select>
<img src="https://www.pexels.com/photos/4141719/pexels-photo-4141719.jpeg" name="selected-image" />

<script> 
    function swapImage(select){
        var img = document.getElementsByName("selected-image")[0];
        img.src = select.options[select.selectedIndex].value;
    }
</script>

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

Shadows persist despite light intensity being reduced to 0 during runtime

Struggling to figure out how to get rid of these persistent shadows... During runtime, I attempt: light.intensity = 0.0; This makes the scene darker (which is good), but the shadows created by the light remain visible. I've experimented with both ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

When is the appropriate time to provide arguments to the constructor of a TypeScript service?

I am grappling with the concept of when to pass arguments to a service's constructor versus passing them in the execution of the service. For instance, I have a service that filters rows from an Excel sheet: @Injectable() export class FilterRowsServi ...

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

Choose a cell from a separate column within a React application

Currently, I've been developing a puzzle game using React JS. My goal is to be able to choose one cell in each column, but I haven't been successful in achieving that yet. You can find the code sample here. Any assistance you can provide would be ...

Creating Dynamic Menus with Material UI

I am currently working on rendering a Material UI Menu for each of my JSX Button Elements. However, all of my Menu Items are currently stacked on top of each other, and I want to be able to display only the Menu related to the clicked Button. Check out th ...

Implement the useState setter functionality within a child component

I need help figuring out how to properly type a useState setter that I'm trying to pass to a child component. const Parent = () => { const [count, setCount] = useState(0); return( Child count={count} setCount={setCount} /> ); } W ...

What types of functions can I link to jQuery's on() event handler?

Are there any additional events that can be used with jQuery's on() function besides click, mouseover, and mouseleave? I have been searching for documentation on this but can't seem to find any. ...

"Flaticon icons display properly when stored on a local server, but encounter issues when accessed online

Working on a website, I have incorporated numerous icons into the design. Despite organizing the files effectively, I am struggling to identify any potential issues. As a beginner in this field, I continue to learn and grow. ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...

"Incorporating input boxes for MySQL updates using PHP, MySQL, and HTML

I'm looking to make my input box dynamic, where it can read the current value from the database and allow users to change that value. Currently, when I enter a number like 1000 into the input box, it posts fine. The PHP results show: Data updated: c ...

Can the ::before selector be used in HTML emails?

Hey there, I have a question that might sound silly but I'm having trouble finding an answer online. My issue is with styling the bullet point before a list item in an HTML email. All I want to do is change the bullet point to a square and give it a ...

I've experimented with binary tree examples and received the output in object form. Now, I'm wondering how I can extract the values from this object and convert them into

Issue Description A tree with N nodes rooted at 1 is given to you. Each node in the tree has a special number Se associated with it. Additionally, each node has a certain Power. The power of each node in the tree is defined as the count of heavy nodes in t ...

Problem with integration of Bootstrap datetime picker in AngularJS directives

I am currently utilizing the Bootstrap Datetime picker to display data from a JSON file in calendar format. The data is first converted into the correct date format before being shown on the calendar, with both a To date and From date available. scope.onH ...

What is the best way to overlay a two-line heading onto an image background?

I'm struggling to position a text heading directly over an image in the center without it getting cut off. Any ideas on how to achieve this? <header class="text-center"> <img src="img\blueskycrop.jpg" class="img-fluid" alt="bluesky"> ...

using CSS to create responsive designs with multiple divs

After spending hours searching, I am still struggling to get two divs to sit next to each other at 50% width each, with a third div below that spans 100% width. The challenge is to make the layout responsive, so that when the screen size is reduced to arou ...

Error: NextJS cannot access the 'map' property of an undefined object

Hey everyone, I usually don't ask for help here but I'm really struggling with this piece of code. I've tried looking at various resources online but can't seem to figure out why it's not working. Any guidance would be greatly appr ...

Blurring the Background with CSS

Greetings! I'm attempting to achieve a background blur effect similar to the image shown. I am curious if this can be accomplished using only CSS3 or if JavaScript & Jquery are necessary for implementation: If CSS alone is sufficient, how can I ens ...

Sharing the same instance of a class across various entry points in webpack output: A guide

Are separate instances of a class created when it is imported into different entry-point files of webpack? I need to import a class called AJAX and maintain the same instance throughout the project across all entry-point files. Currently, AJAX is used as ...

What is the best way to send an observable with parameters through @Input?

The objective is to transfer an http request from Component 1 to Component 2 and initialize its parameters on Component 2. Here is a pseudo code representation of my approach: Component 1 HTML <app-component-2 [obs]="obs"></app-component-1> ...