user2019346
user2019346

Reputation: 13

Dynamically changing photo with dropdown

I am new to PHP and am trying to figure out how to code some specific functionality. I have a product page that shows a photo and has two dropdown menus, one for size and one for color. What I would like to do is when the page first loads I set a variable that has the default product SKU. When the menus change I want to change the variable to the combined values of the two menu items selected. As the variable changes I want to reflect this in the photo and in a hidden form value (for eventual submission to a cart).

So when the page loads it shows picture A with the associated values in the size and color dropdowns. Then when either of the dropdowns change the photo dynamically changes to reflect it (while also updating the hidden form value).

Any suggestions would be much appreciated.

Upvotes: 1

Views: 1340

Answers (2)

PlantTheIdea
PlantTheIdea

Reputation: 16359

JavaScript, or a JS library like jQuery, is what you need here.

For jQuery (preferred, way easier):

var $select = $('#Dropdown'),
    $img = $('#Picture');

$select.on('change',function(){
    $img.attr('src',$(this).val());
});

For JavaScript:

var dropdown = document.getElementById('Dropdown'),
    img = document.getElementById('Picture');

dropdown.addEventListenter('change',function(){
    img.src = this.value;
});

Not tested, but should work.

Edit: when using the JavaScript solution, make sure the window is loaded first (it won't work if the elements dont exist yet).

window.onload = function(){
    // do your magic here
}

Upvotes: 3

Ben Carey
Ben Carey

Reputation: 16948

Firstly, PHP is a server side language which effectively means, anything that it generates must be processed by the server and then sent back to the browser. Therefore in this particular case, you need to use a client side language such as Javascript, or to make the code easier, a library such as jQuery.

To learn more about jQuery, see here:

http://jquery.com/

In very generalised terms (as you have not posted any code), here is an example of changing an image using jQuery:

// Select the dropdown from the DOM
var dropdown = $('#dropdown_id');

// Select the image from the DOM
var image = $('#image');

// Set the onchange event
// This will be fired when the select value is changed
dropdown.on('change',function(){
    // Get the value of the selected option
    var value = $(this).val();

    // Change the source of the image
    image.attr('src',value);
});

Upvotes: 2

Related Questions