FrK
FrK

Reputation: 89

Javascript function on particular select value

I hope someone can help me with some troubles I'm having. I'm working on a webshop in which it is possible to buy a product in multiple colours. I want to make a select box in which all available colours are stored and when you choose "Green" in the select box, the image of the product changes to the image of the product in green! I already made some sort of script that does what I want but I'm not satisfied yet.

All the available colours are loaded to the vars colours from a database, so it's pretty important to keep this part intact.

 var colours = {
     'red': 'http://i39.tinypic.com/2mgru6b.jpg',
     'blue':'http://i40.tinypic.com/5losqu.jpg',
 };

This is the img element in which the images are loaded into:

 <img src="http://i43.tinypic.com/2rw0v0m.jpg" id="preview-img">

And this is the function:

 window.showColour = function(colour) {
      var url = colours[colour];
      var img = document.getElementById('preview-img');
      img.src = url;
 };

Right now I'm calling the function by a simple link:

 <a href="javascript:showColour('red');">Red</a>
 <a href="javascript:showColour('blue')">Blue</a>

To see this all working: http://jsfiddle.net/92Ht6/5/

But the thing I want is that the function isn't being called by a simple link, I want the function to be executed when you select 'red' in the select box (showColour('red'); or when you select blue in the select box (showColour('blue');

Thanks in advance!

Upvotes: 0

Views: 59

Answers (2)

Guffa
Guffa

Reputation: 700422

Use the change event in the select box:

<select id="colour">
  <option value="red">Nice red colour</option>
  <option value="blue">Cool blue colour</option>
</select>

jQuery to bind the event:

$(function(){
  $('#colour').change(function(){
    showColour($(this).val());
  });
});

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Considering you don't have a select, create one like the following:

<select id='colors'>
    <option value='green'>Green</option>
    ..
    ..
</select>

Then the onchange event:

document.getElementById("colors").onchange = function() {
    var value = this.options[this.selectedIndex].value;
    showColour(value);
}

Edit: Just saw the jQuery tag :\

Upvotes: 2

Related Questions