To change src image for <input type="image"

Thanks in Advance…

I have a img tag :
<input type=“image” src=“…/abc.gif” name=“img” onclick=“clicked();”/>

My issue is…

in clicked js i want to change src to …/def.gif so that i can change the src dynamically …

I tried acessing src using id,name attributes nothing worked to me…Plz give ur valuable suggestions…

within your clicked function you can pass back the element that was clicked by using

 <input type="image" src="../abc.gif" name="img" onclick="clicked(this);"/> 

then your javascript function clicked would be like


function clicked(what) {
                what.src = '../def.gif';
            }

Microsoft’s IE won’t be able to easily find the image because when you’re using the inline event registration, IE doesn’t have the this keyword reference the element, instead it just references the window itself.
See http://www.quirksmode.org/js/this.html

To remedy this you should use the traditional event registration instead, which has the nice effect of keeping the javascript separate from the html.


<input type="image" src="../abc.gif" name="img" />


var el = document.getElementsByName('img')[0];
el.onclick = clicked;

I’m confused… Every time i’ve used the this keyword within an inline event, it’s worked. Regardless of the browser?!

Using the this keyword works, when you explicitly specify it.
It’s also supposed to be automatically available, but Microsoft loses it when using inline event registration.

When specified inline and explicitly defined, the this keyword passes the element but it needs to be picked up in the function as a variable.


<div id="myDiv" onclick="doSomething(this)">


doSomething(el) {
    // works with all browsers
}

When the inline event is called without passing the this keyword as a parameter, the function won’t be able to use the this keyword to reference the element from IE.


<div id="myDiv" onclick="doSomething()">


doSomething() {
    var el = this; // doesn't work with IE inline event registration
}

Using inline event registration has those poblems.

Traditional event registration is where the this keyword is automatically available from all browsers


<div id="myDiv">


document.getElementById('myDiv').onclick = doSomething;
doSomething() {
    var el = this; // works on all browsers with traditional event registration
}

This last technique is the preferred one to use for flexibility and ease of use.
When testing, it’s also possible to explicitly pass a refrerence for the this keyword, that is to be used within the called function.


var el = document.getElementById('myDiv');
doSomething.call(el, text);
function doSomething(text) {
    // the this keyword refers to el
}