user1649795
user1649795

Reputation: 31

How to create an IMG when I click on a button?

Now I have this:

<script>
 function load() { 
 var el = document.getElementById('load');
 el.innerHTML='<img src=\"load.png\">'; }
</script>

And the html:

<input type="submit" onclick="javascript:load();"> 
<span id="load"> </span>

but that doesn't work, because i may not put < and > within the el.innerHTML=''. Does anyone know an alternative?

TIA

Upvotes: 3

Views: 158

Answers (4)

Maxim VA
Maxim VA

Reputation: 398

You might try this:

javascript:

 function showImage(){
     document.getElementById('load').style.display = 'block';
  }

html:

 <input type="submit" onclick="showImage();">
 <span id="load" style="display:none;"><img src="load.png"></span>

Upvotes: -1

Michal Klouda
Michal Klouda

Reputation: 14521

You should create the element using createElement() method and then append it to your container:

var el = document.getElementById('load');
var img = document.createElement('img');
img.src = 'test.png';
el.appendChild(img);
alert(el.innerHTML);

See this DEMO.

Upvotes: 0

Quentin
Quentin

Reputation: 943220

The whole point of innerHTML is that you can use < and > inside it. You have some pointless escaping of quotes, and the cargo-cult javascript: label, but the script works.

It probably just looks like it is failing because the form submits and the browser leaves the page before the image loads.

Upvotes: 2

pmandell
pmandell

Reputation: 4328

Use jQuery!

<button id="button">Click</button>

$(document).ready(function(){
    $("#button").click(function(){
        $("#load").append("<img src='\load.png\'/>");
    });
});

Upvotes: 0

Related Questions