forms - Change images from a select field using Javascript -
so i'm trying change image based on option user selects dropdown menu. images "cyan.png", "magenta.png", "yellow.png", "black.png", , "fuschia.png".
my html
<select name="color" multiple> <option>cyan</option> <option>magenta</option> <option>yellow</option> <option>black</option> <option>fuschia</option> </select>
my javascript
// part tries load images onto cararray variable var namearray = new array("cyan.png", "magenta.png", "yellow.png", "black.png", "fuschia.png"); var cararray = new array; for(var = 0; < cararray.length; i++) { cararray[i] = new image; cararray[i].src = namearray[i]; } // part tries (and fails) change image when user selects color dropdown menu window.onload = function() { var colorpicker = document.getelementsbyname("color").selectedindex; var options = document.getelementsbyname("color").options; document.getelementbyid("photo").src = cararray[options[colorpicker]; }
could please me understand problem is, , how fix it.
if bind function on window.onload
, fire once @ windows loading. want bind on select onchange
event.
e.g.:
function pickcolor() { var colorpicker = document.getelementsbyname("color").selectedindex; var options = document.getelementsbyname("color").options; document.getelementbyid("photo").src = cararray[options[colorpicker]]; } <select name="color" onchange="pickcolor()" multiple> ...
as @lightstyle suggests, should avoid inline event assignments. don't know dom, simplicity i'll add id (it must unique in page) select. can following:
document.getelementbyid('color').onchange = function() { var colorpicker = document.getelementsbyname("color").selectedindex; var options = document.getelementsbyname("color").options; document.getelementbyid("photo").src = cararray[options[colorpicker]]; } <select name="color" id="color" multiple>
Comments
Post a Comment