Alter select options upon image switch using JavaScript

I have a simple JavaScript code that changes an image when buttons are clicked. I would like to integrate this functionality with a select statement so that the corresponding option is also changed every time a button is clicked.

<img src="https://robinsonswoodcrafts.com/images/StainColors/11_maple_EnglishChestnut.jpg" id="stainImage" alt="">
    <p>
        <button onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Goldenoak.jpg'">Golden Oak</button>
        <button onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Natural.jpg'">Natural</button>
        <button onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Earlyamerican.jpg'">Early American</button>
        <button onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_RedMahogany.jpg'">Red Mahogany</button>
        <button onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Puritanpine.jpg'">Puritan</button>
    </p>

The stain colors displayed in the images correspond with the options in a select element which will be part of an order form using a shopping cart. The select statement looks like this:


           <div class="form__item">
                <label for="staincolor" class="form__label">Stain Color</label>
                    <select name="staincolor" id="stainColor">
                        <option value="">[ No Stain ]</option>
                        <option id="sc-goldenoak" value="Golden Oak {p+1.50}">
                            Golden Oak
                        </option>
                        <option id="sc-natural" value="Natural {p+1.50}">
                            Natural
                        </option>
                        <option id="sc-earlyamerican" value="Early American {p+1.50}">
                            Early American
                        </option>
                        <option id="sc-redmahogany" value="Red Mahogany {p+1.50}">
                            Red Mahogany
                        </option>
                        <option id="sc-puritanpine" value="Puritan Pine {p+1.50}">
                            Puritan Pine
                        </option>
                </select>
          </div>

Answer №1

One approach could be to organize your variants with corresponding filenames or vice versa. Then, you can create a simple function for your buttons that will handle both changing the image and selecting the option in your select input.

const files = {
  'Golden Oak {p+1.50}': '1_pine_Goldenoak.jpg',
  'Natural {p+1.50}': '1_pine_Natural.jpg'
}

function chooseColor(option) {
  document.getElementById('stainImage').src = 'https://example.com/images/' + files[option];
  document.getElementById('stainColor').value = option
}
<img src="https://example.com/images/1_pine_Goldenoak.jpg" id="stainImage" alt="">
<p>
  <button onclick="chooseColor('Golden Oak {p+1.50}')">Golden Oak</button>
  <button onclick="chooseColor('Natural {p+1.50}')">Natural</button>
</p>

<div class="form__item">
  <label for="staincolor" class="form__label">Stain Color</label>
  <select name="staincolor" id="stainColor">
    <option value="">[ No Stain ]</option>
    <option id="sc-goldenoak" value="Golden Oak {p+1.50}">
      Golden Oak
    </option>
    <option id="sc-natural" value="Natural {p+1.50}">
      Natural
    </option>
  </select>
</div>

Answer №2

Implementing event delegation...

const imgPath    = 'https://example.com/images/StainColors/'
  ,   r_ImgBtSel =
    [ { lib: 'Golden Oak',     val: 'Golden Oak {p+1.50}',     img: '1_pine_Goldenoak.jpg'     }
    , { lib: 'Natural',        val: 'Natural {p+1.50}',        img: '1_pine_Natural.jpg'       }
    , { lib: 'Early American', val: 'Early American {p+1.50}', img: '1_pine_Earlyamerican.jpg' }
    , { lib: 'Red Mahogany',   val: 'Red Mahogany {p+1.50}',   img: '1_pine_RedMahogany.jpg'   }
    , { lib: 'Puritan',        val: 'Puritan Pine {p+1.50}',   img: '1_pine_Puritanpine.jpg'   }
    ]
const stainImage = document.getElementById('stainImage')
  ,   grpBtns    = document.getElementById('group-buttons-xyz')
  ,   stainColor = document.querySelector('select#stainColor')
  ;
r_ImgBtSel.forEach(el=>  
  {
  let bt = document.createElement('button')
  bt.textContent = el.lib
  grpBtns.appendChild(bt)
  stainColor.add( new Option(el.lib, el.val))
  })
grpBtns.onclick = ev => 
  {
  if (!ev.target.matches('button')) return  
  let info = r_ImgBtSel.find(x=>x.lib===ev.target.textContent ) 
  stainImage.setAttribute('src', imgPath + info.img )  
  stainColor.value = info.val                          
  }
stainColor.onchange =e=>
  {
  let info = r_ImgBtSel.find(x=>x.val===stainColor.value )
  stainImage.setAttribute('src', imgPath + info.img )  
  }
 
<img id="stainImage" src="https://example.com/images/StainColors/11_maple_EnglishChestnut.jpg" alt="">

<p id="group-buttons-xyz"></p>

<div class="form__item">
  <label for="staincolor" class="form__label">Stain Color</label>
    <select name="staincolor" id="stainColor">
      <option value="" selected disabled >[ No Stain ]</option>
    </select>
</div>

Answer №3

Give this a try - it definitely works :)

let button = document.getElementsByClassName('btn');
let stainColor = document.getElementById('stainColor');

Array.from(button).forEach(ele => {
      ele.addEventListener('click', (e) => {
            
            stainColor.value = e.target.innerHTML + ' {p+1.50}'
           
            
       })
       
});
<img src="https://robinsonswoodcrafts.com/images/StainColors/11_maple_EnglishChestnut.jpg" id="stainImage" alt="">
    <p>
        <button class="btn" onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Goldenoak.jpg'">Golden Oak</button>
        <button class="btn" onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Natural.jpg'">Natural</button>
        <button class="btn" onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Earlyamerican.jpg'">Early American</button>
        <button class="btn" onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_RedMahogany.jpg'">Red Mahogany</button>
        <button class="btn" onclick="document.getElementById('stainImage').src='images/StainColors/1_pine_Puritanpine.jpg'">Puritan</button>
    </p>

<div class="form__item">
                <label for="staincolor" class="form__label">Stain Color</label>
                    <select name="staincolor" id="stainColor">
                        <option value="">[ No Stain ]</option>
                        <option id="sc-goldenoak" value="Golden Oak {p+1.50}">
                            Golden Oak
                        </option>
                        <option id="sc-natural" value="Natural {p+1.50}">
                            Natural
                        </option>
                        <option id="sc-earlyamerican" value="Early American {p+1.50}">
                            Early American
                        </option>
                        <option id="sc-redmahogany" value="Red Mahogany {p+1.50}">
                            Red Mahogany
                        </option>
                        <option id="sc-puritanpine" value="Puritan {p+1.50}">
                            Puritan Pine
                        </option>
                </select>
          </div>

Answer №4

Here is a solution that I have come up with for you:

    const products={
                        "Chair":{
                            "imgSrc":"images/Furniture/chair.jpg",
                            "productId":"product-chair"
                        },
                        "Table":{
                            "imgSrc":"images/Furniture/table.jpg",
                            "productId":"product-table"
                        },
                        "Sofa":{
                            "imgSrc":"images/Furniture/sofa.jpg",
                            "productId":"product-sofa"
                        },
                        "Desk":{
                            "imgSrc":"images/Furniture/desk.jpg",
                            "productId":"product-desk"
                        },
                        "Bed":{
                            "imgSrc":"images/Furniture/bed.jpg",
                            "productId":"product-bed"
            }
                    };
          
function displayProduct(key){
    var img=document.getElementById("productImage");
  img.src=products[key].imgSrc;
  document.getElementById(products[key].productId).selected=true;    
  
}
<img src="https://example.com/images/Furniture/default.jpg" id="productImage" alt="">
<p>
  <button onclick="displayProduct(this.textContent)">Chair</button>
  <button onclick="displayProduct(this.textContent)">Table</button>
  <button onclick="displayProduct(this.textContent)">Sofa</button>
  <button onclick="displayProduct(this.textContent)">Desk</button>
  <button onclick="displayProduct(this.textContent)">Bed</button>
</p>

<div class="form__item">
  <label for="productType" class="form__label">Select Product Type:</label>
  <select name="productType" id="productType">
    <option value="">[ Select Product ]</option>
    <option id="product-chair" value="Chair {price+50}">
      Chair
    </option>
    <option id="product-table" value="Table {price+100}">
      Table
    </option>
    <option id="product-sofa" value="Sofa {price+200}">
      Sofa
    </option>
    <option id="product-desk" value="Desk {price+80}">
      Desk
    </option>
    <option id="product-bed" value="Bed {price+150}">
      Bed
    </option>
  </select>
</div>

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

Utilizing jQuery's fadeIn() and fadeOut() functions can lead to a significant decrease

I recently added a loading indicator in the form of an animated .svg with fadeIn and fadeOut effects to display it on my webpage alongside an animated canvas. However, I noticed a significant decrease in the performance of my canvas during these operations ...

Tips for concealing the angular component depending on a specific circumstance

I have developed a custom directive for validating input. It is designed to check the length of the input. If the length is zero, an error message will be displayed. However, I am facing difficulty in hiding the error message when the input is filled with ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

Prevent Previous/Next Buttons, Autofill, and Completion Bar on iPhone Web Forms

Can the bar on web forms that includes the (Previous|Next) Autofill and Done button be disabled or suppressed? I know there are solutions for native apps, but I am specifically working on a web app. I'm wondering if there is a simple attribute to add ...

PHP - designate a separate folder for script and style resources

There seems to have been some discussion about this issue before, but I am struggling to find a solution. I want to add css, js, and asset files to my php framework. However, when calling these files, the path must always match the folder structure like t ...

jQuery rounded images slideshow

Currently, I am working on developing a jquery slider that showcases rounded images. Below is the HTML code: jQuery(document).ready(function($) { var $lis = $('ul').find('li'), length = $lis.length; $lis.each(function( ...

Using the Javascript $.each method to iterate over elements

this.CurrentComponent.ExtendedProperties is a Dictionary<string, string> obtained from the .Net platform. However, when trying to access the values within this Dictionary on the client side using JavaScript, all objects associated with the property a ...

How to retrieve all user_notes in Rails 6 using Bootstrap 5 and Ajax Calls, instead of only fetching the notes belonging to the current

I'm struggling with a issue related to my joined table called user_notes, which connects an adventure_id with a user_id (belongs_to) and includes a longtext field called :note. The problem I'm facing is that all users can see each other's no ...

Use the same CSS style for various attribute selectors

Is there a way to simultaneously apply the following style to a type="submit" without having to repeat the entire block of code? input[type="button"] { width: 120px; margin-left: 35px; display: block; } ...

Javascript code that fires when all elements are loaded

Incorporating two external HTML pages using the following code: <div id="header-div"></div> <div id="footer-div"></div> This is what my JavaScript file consists of: $(function () { $("#header-div").load("/AfekDent/header.ht ...

The process of comparing two arrays of objects in es6 and filtering out the unmatched arrays

In my Angular application, I'm attempting to retrieve only the updated array that was modified from the user interface. Within this scenario, I have two arrays in which one of the role names has been changed. My goal is to compare and extract the mod ...

The React Navbar fails to appear when using React JS

I am currently in the process of creating a single-page website. I have incorporated react-bootstrap for the navigation bar, but I am facing an issue where it is not rendering on the page. Despite not encountering any errors, the page remains blank. Below ...

What is the main file that vue-cli-service utilizes for entry?

Interested in a project utilizing vue, webpack, babel, npm? You can launch it with npm run server. While exploring how this command functions, I came across vue-cli-service serve in the package.json file. But how exactly does vue-cli-service initialize ...

What is the procedure for employing suitscript within Restlet in the NetSuite environment?

Currently, I am working on creating a restlet in Netsuite to retrieve details about a specific Field. The code snippet I have been using is as follows: error code: UNEXPECTED_ERROR error message:TypeError: Cannot call method "getType" of null (login.js$12 ...

The Bootstrap command to show the modal with the ID "myModal" is malfunctioning

For some reason, I am having trouble with all the modal functions not working properly. I have checked the version and the load, and everything seems to be fine. An error message that keeps popping up is: Uncaught TypeError: $(...).modal is not a functio ...

Is there a way to establish a default value following actions in useEffect when utilizing custom hooks?

Using React with Hooks and Redux saga, the page is rendered. The useEffect then takes actions to retrieve company information, causing the page to re-render. However, variables like name and location, used with useInput, do not set initialData from selComp ...

A pair of demands within an express service

Currently, I'm facing an issue in a project where I am attempting to create a service using Express that makes two external API calls. However, I am encountering an error in Express that is difficult to comprehend. It seems like my approach might be i ...

What are the implications of employing a singular global variable for angular modules?

After coming across a template, I noticed that the variable anApp is declared once in app.js and then shared among all modules. This has led me to wonder: 1. Will using a single variable result in all Angular components being stored in the global scope? 2. ...

Trouble with virtual canvas when attempting to put image data

I am new to the virtual canvas concept and I'm having trouble with the code below. Can anyone help me figure out why it's not working? <script type="text/javascript"> $(document).ready(function () { var c1 = docu ...

What is the jQuery Autocomplete syntax like?

Though my experience with jQuery is limited, I have successfully implemented Autocomplete code that highlights the search characters in the dropdown rows: .autocomplete({ delay: 500, minLength: 0, source: function(request, response) { ...