Chucky Chan
Chucky Chan

Reputation: 75

Displaying an image when selecting an option from a drop down list

I'm trying to change an image upon selection of an option in a drop down list:

function volvoCar()
{
var img = document.getElementById("image");
img.src="volvo.png";
return false;
}

And so on for each car.

<img id="image" src="Null_Image.png"/>
<select id="CarList">
<option onclick="nullCar()">No Car</option>
<option onclick="volvoCar()">Volvo</option>
<option onclick="audiCar()">Audi</option></select>

I can't seem to find anything online that gives me a solution. Whether it's because I'm phrasing it awkwardly or because what I'm trying to do is impossible with javascript, I don't know.

Upvotes: 2

Views: 26932

Answers (2)

phenomnomnominal
phenomnomnominal

Reputation: 5515

Okay, you're doing several things wrong.

  1. Your function is called volvoCar and you are attempting to use a function called VolvoCar - JavaScript is case sensitive.

  2. This isn't the best way to assign an event-listener. You're adding it in the HTML, which is considered 'messy' (see Unobtrusive JavaScript). Also, you want to attach the function, not the result of the function (which you are doing by calling it). Functions are first-class objects in JavaScript.

  3. onclick is the wrong event handler to use in this case. You want to use the onchange handler of the <select> element.

So:

HTML:

<img id="image" src="Null_Image.png"/>
<select id="CarList">
    <option value="Null">No Car</option>
    <option value="Volvo">Volvo</option>
    <option value="Audi">Audi</option>
</select>

JS:

var changeCarImage = function () { 
    document.getElementById('image').src = this.options[this.selectedIndex].value + "_Image.png"
}

var carList = document.getElementById('CarList');
carList.addEventListener('change', changeCarImage, false); // Note this has some issues in old browsers (IE).

This can be seen working here!

Upvotes: 1

Trey Hunner
Trey Hunner

Reputation: 11814

Instead of setting the onClick event for an option, set the onChange event for the select.

HTML

<img id="image" src="Null_Image.png" />
<select id="CarList">
    <option value="Null_Image.png">No Car</option>
    <option value="volvo.png">Volvo</option>
    <option value="audi.png">Audi</option>
</select>

JavaScript

function setCar() {
    var img = document.getElementById("image");
    img.src = this.value;
    return false;
}
document.getElementById("CarList").onchange = setCar;

Here's a working demo

Upvotes: 2

Related Questions