1

I want to change the <img src> with value from my <select>.

I have the next HTML code:

<img id="fotosel" /><br/>
<select id="cmbfotos" onchange="aplicarFoto()">
    <option value="gokussj3.jpg">Goku SSJ3</option>
    <option value="gokussj4.jpg">Goku SSJ4</option>
    <option value="gohanssj2.jpg">Gohan SSJ2</option>
    <option value="gotenks.jpg">Super Gotenks</option>
    <option value="krilin.jpg">Krilin</option>
</select> 

and Javascript code:

 var fotosel = document.getElementById("fotosel");
    var cmb = document.getElementById("cmbfotos");
    function aplicarFoto(){
    fotosel.src = "fotos/"+cmb.options[cmb.selectedIndex].value;

   }

But that doesnt work. I made a test putting an alert() with cmb.options[cmb.selectedIndex].value and nothing appears. Some guess? Thank you!

1
  • Seems to get the right value for me: jsfiddle.net/EMTPw Maybe something else on your page? Commented May 28, 2013 at 3:15

2 Answers 2

3

Change your aplicarFoto() function to:

function aplicarFoto(_src) {
    fotosel.src = 'fotos/' + _src;
}

and in your HTML:

<select id="cmbfotos" onchange="aplicarFoto(this.value)">
    ...
</select>
Sign up to request clarification or add additional context in comments.

2 Comments

@Isaac - Probably because i missed the 'fotos/' prefix. :-)
Thank you, but My problem was that I declared my variable outside the function... :) anyways your answer resolved my problem! :D
0

Try this

<img id="fotosel" /><br/>
<select id="cmbfotos" onchange="aplicarFoto(this.value)">
    <option value="gokussj3.jpg">Goku SSJ3</option>
    <option value="gokussj4.jpg">Goku SSJ4</option>
    <option value="gohanssj2.jpg">Gohan SSJ2</option>
    <option value="gotenks.jpg">Super Gotenks</option>
    <option value="krilin.jpg">Krilin</option>
</select>

Javascipt :

    var fotosel = document.getElementById("fotosel");

     function aplicarFoto(elmImage){
        fotosel.src = "fotos/"+elmImage;
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.