How to change the image according to a variable coming from the bank?

Asked

Viewed 520 times

0

I’m a beginner in this part of front-end and made a function that returns an entire number from my Mysql database. I created 5 images, each one corresponds to a number returned from the bank and attached in my folder imgs of the project.

I found that the value is being passed to the page JSP no problems, but I wonder how I do a function in Javascript to call the image according to the number returned by the bank and the tag HTML5 to be used in my code.

Currently my Javascript code is this:

  function mudaFoto(status){
         var fotos = ["imgs/panel/img-painel-02-01.png","imgs/panel/img-painel-02-02.png","imgs/panel/img-painel-02-03.png","imgs/panel/img-painel-02-04.png","imgs/panel/img-painel-02-05.png"];
                if(status==1){
                         document.getElementById("icone").src=fotos[0];
                }
                else{
                if(status==2){
                    document.getElementById("icone").src=fotos[1];
                }
                else{
                if(status==3){
                    document.getElementById("icone").src=fotos[2];
                }
                else{
                if(status==4){
                    document.getElementById("icone").src=fotos[3];
                }
                else{
                    document.getElementById("icone").src=fotos[4];
                }
            }
        }
    }

}

My code in HTML:

< img id="icone" img="imgs/panel/img-painel-02-01.png" alt="imagem de status" class="img-responsive" />
  • change the "img" attribute of your <img> to "src" !

1 answer

1

Its function mudaFoto(status) is OK.

Your img tag lacks the src attribute

<img id="icone" src="imgs/panel/img-painel-02-01.png" img="imgs/panel/img-painel-02-01.png" alt="imagem de status" class="img-responsive" />

You can use event onload directly in its function or tag <body> (modern versions of Javascript also accept other elements such as tag <img>).

examples:

  • Direct in function

     window.onload = function mudaFoto(status){ 
     .................
     .................
    
  • In the tag img

    <img id="icone" ..... onload="mudaFoto(numeroDoBanco)" />
    
  • In the tag body

    <body onload="mudaFoto(numeroDoBanco)">
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.