user2692541
user2692541

Reputation:

Load an image using the SELECT element

I have this html code which work fine. I want load the flag's image when select an option and then use the option value for my database.

<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" onchange="changeTest()" name="select1">
    <option value="0">USA</option>
    <option value="1">AUSTRALIA</option>
    <option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img> 

imageArray = new Array("usa.gif", "australia.gif", "canada.gif");
altArray = new Array("USA", "AUSTRALIA", "CANADA");

function changeTest () 
{ 
    var Index = document.countriesForm.select1.options[document.countriesForm.select1.selectedIndex].value;
    document.flags.src = imageArray[Index]; document.flags.alt = altArray[Index];   
}

Upvotes: 0

Views: 51

Answers (2)

Deepak Biswal
Deepak Biswal

Reputation: 4320

This will do the trick. Here is the demo.

HTML

<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" name="select1">
    <option value="0">USA</option>
    <option value="1">AUSTRALIA</option>
    <option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img> 

JS

(function(){
 var imageArray = new Array("usa.gif", "australia.gif", "canada.gif");
var altArray = new Array("Default", "Round", "Frame", "Pink Star");

    document.getElementById('select1').onchange = function() {
        var e = document.getElementById('select1');
        var index = e.options[e.selectedIndex].value;
        var targetImg = document.getElementById('flags');
        targetImg.src = imageArray[index];
        targetImg.alt = altArray[index];   
    };
})();

Upvotes: 1

Chris
Chris

Reputation: 1829

this will do it:

document.getElementById('select1').onchange = function() {
    var index = this.options[this.selectedIndex].value;
    document.flags.src = imageArray[index];
    document.flags.alt = altArray[index];
    //alert(imageArray[index]);
};

http://jsfiddle.net/5dkdm5ge/1/

Upvotes: 0

Related Questions