Here is my code:
HTML
<form>
<img id='image' src=""/>
<input type='text' id='text'>
<input type="button" value="change picture" onclick="changeimage()">
</form>
JavaScript
function changeimage() {
var a=document.getElementById('text').value
var c=a+".gif"
c="\""+c+"\""
var b= "<img src="+c+"\/>"
document.getElementById('image').innerHTML=b
}
I have some GIF images. I want to write an image name in the textbox and then have the image bee shown when the button is clicked. However, it's not happening. Why?
Here is my code:
HTML
<form>
<img id='image' src=""/>
<input type='text' id='text'>
<input type="button" value="change picture" onclick="changeimage()">
</form>
JavaScript
function changeimage() {
var a=document.getElementById('text').value
var c=a+".gif"
c="\""+c+"\""
var b= "<img src="+c+"\/>"
document.getElementById('image').innerHTML=b
}
I have some GIF images. I want to write an image name in the textbox and then have the image bee shown when the button is clicked. However, it's not happening. Why?
Share Improve this question edited Jul 26, 2012 at 14:20 merv 76.9k17 gold badges214 silver badges277 bronze badges asked Jan 17, 2012 at 17:41 sovonsovon 9072 gold badges13 silver badges30 bronze badges 04 Answers
Reset to default 9You should do this:
document.getElementById('image').src = c;
By doing document.getElementById('image').innerHTML=b
you are trying to defined the HTML inside the <img>
tag which is not possible.
Full script:
function changeimage() {
var a = document.getElementById('text').value;
var c = a + ".gif";
document.getElementById('image').src = c;
}
Try this instead:
<html>
<body>
<script type="text/javascript">
function changeimage() {
var a = document.getElementById('text').value;
document.getElementById('image').src = a + '.gif';
}
</script>
<form>
<img id='image' src=""/>
<input type='text' id='text'>
<input type="button" value="change picture" onclick="changeimage()">
</form>
</body>
</html>
document.getElementById("image").setAttribute("src","another.gif")
In order to update the <img>
tag you need to update it's source, not it's inner HTML.
function changeimage()
{
var a=document.getElementById('text').value
var c=a+".gif"
c="\""+c+"\""
var elem = document.getElementById('image');
elem.setAttribute('src', c);
}