scoots
scoots

Reputation: 294

Changing image with dropdown menu

I am trying to change an image depending on what option is selected in a drop down menu. I am very new to javascript, so I am sure that it is a small problem that I'm not noticing. My attempt at implementing it is below:

JS:

<script type="text/javascript">             
    function setPicture() {
        var img = document.getElementById("coffeedropdown");
        var value = coffeedropdown.options[coffeedropdown.selectedIndex].value;
        alert(selectedValue);
    }
</script>

HTML:

<select id="coffeedropdown" onchange="setPicture();">
    <option value="../Images/pimms.jpg">Select a Drink</option>
    <option value="../Images/caffe.jpg">Caffe</option>
    <option value="../Images/caffelatte.jpg">Caffe Latte</option>
    <option value="../Images/cappuccino.jpg">Cappuccino</option>
    <option value="../Images/marocchino.jpg">Caffee Marrocchino</option>
    <option value="../Images/americano.jpg">Caffe Americano</option>
    <option value="../Images/shakerato.jpg">Caffe Shakerato</option>
    <option value="../Images/corretto.jpg">Caffe Corretto</option>
</select>

If anyone could help me out with this, I would really appreciate it! Thanks.

Upvotes: 0

Views: 9426

Answers (3)

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You don't have coffeedropdown variable declared or initialized anywhere, so after initializing img variable with your dropdown you need img to be used further, as your coffedropdown will be now img.

var img = document.getElementById("coffeedropdown");
var value = coffeedropdown.options[coffeedropdown.selectedIndex].value;

should be

var img = document.getElementById("coffeedropdown");
var value = img.options[img.selectedIndex].value;
            ^^^         ^^^ //img here not coffeedropdown

Fiddle

Upvotes: 2

Tuhin
Tuhin

Reputation: 3373

Simplest Method:)

<select id="coffeedropdown" onchange="setPicture(this);">
            <option value="../Images/pimms.jpg">Select a Drink</option>
            <option value="../Images/caffe.jpg">Caffe</option>
            <option value="../Images/caffelatte.jpg">Caffe Latte</option>
            <option value="../Images/cappuccino.jpg">Cappuccino</option>
            <option value="../Images/marocchino.jpg">Caffee Marrocchino</option>
            <option value="../Images/americano.jpg">Caffe Americano</option>
            <option value="../Images/shakerato.jpg">Caffe Shakerato</option>
            <option value="../Images/corretto.jpg">Caffe Corretto</option>
        </select>
    <script type="text/javascript">

        function setPicture(select) {
            selectedvalue=select.value;
            alert(selectedvalue);
        }
    </script>

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20408

Try this

function setPicture() {
    var img = document.getElementById("coffeedropdown");
    var value = img.options[coffeedropdown.selectedIndex].value;
    alert(value);
}

DEMO

Upvotes: 1

Related Questions