Programmatically change the src of an img tag
How can I change the src
attribute of an img
tag using javascript?
<img src="../template/edit.png" name=edit-save/>
at first I have a default src which is "../template/edit.png" and I wanted to change it with "../template/save.png" onclick.
UPDATED: here's my html onclick:
<a href='#' onclick='edit()'><img src="../template/edit.png" id="edit-save"/></a>
and my JS
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
I've tried inserting this inside the edit(), it works but need to click the image twice
var edit_save = document.getElementById("edit-save");
edit_save.onclick = function(){
this.src = "../template/save.png";
}
Solution 1:
Give your img tag an id, then you can
document.getElementById("imageid").src="../template/save.png";
Solution 2:
You can use both jquery and javascript method: if you have two images for example:
<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">
1)Jquery Method->
$(".image2").attr("src","image1.jpg");
2)Javascript Method->
var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"
For this type of issue jquery is the simple one to use.
Solution 3:
if you use the JQuery library use this instruction:
$("#imageID").attr('src', 'srcImage.jpg');
Solution 4:
its ok now
function edit()
{
var inputs = document.myform;
for(var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var edit_save = document.getElementById("edit-save");
edit_save.src = "../template/save.png";
}
Solution 5:
Give your image an id. Then you can do this in your javascript.
document.getElementById("blaah").src="blaah";
You can use this syntax to change the value of any attribute of any element.