简体   繁体   中英

Pass image source to <img> on button click event

I am getting user ID on fly and will use it to show the user image. For that I want to set the img path when user click on button. HEre is code:

HTML:

<img id="i1" style="display:none" src="" > </img>
<button typye="submit"  onclick="CallAfterLogin()"> Show image </button>

JS:

function CallAfterLogin() {
   var path = "http://thestylishdog.com/wp-content/uploads/2009/07/cute-dog2.jpg";
   document.getElementbyID(i1).src = path;
   document.getElementbyID(i1).display = "block";
}

Fiddle:

http://jsfiddle.net/karimkhan/qeyRK/2/

What's wrong?

Here is a syntactically correct version of your handler:

function CallAfterLogin() {
    var path = "http://thestylishdog.com/wp-content/uploads/2009/07/cute-dog2.jpg";

    var imgEl = document.getElementById("i1");

    imgEl.src = path;
    imgEl.style.display = "block";
}

However, the real trick here is with JSFiddle. You have to look in Frameworks and Extensions and switch from onLoad to No wrap - in <body> , as explained in this answer .

Here is a working JSFiddle: http://jsfiddle.net/PpbnG/2/

This should fix it:

  • replace document.getElementbyID(i1) with document.getElementById("i1")
  • replace document.getElementbyID(i1).display with document.getElementById("i1").style.display

Full working function:

function CallAfterLogin() {
   var path = "http://thestylishdog.com/wp-content/uploads/2009/07/cute-dog2.jpg";
   document.getElementById("i1").src = path;
   document.getElementById("i1").style.display = "block";
}
function CallAfterLogin(){
        var path="http://thestylishdog.com/wp-content/uploads/2009/07/cute-dog2.jpg";
        document.getElementById("i1").src=path;
        document.getElementById("i1").style.display="block";
        }

Would it be easier if you just add onclick event to the button

onclick="document.getElementById('i1').style.display='block' "

just one line and job done. You can put the image path in the src with default display set to none, and when you click the image displays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM