Sudha Sarath
Sudha Sarath

Reputation: 17

How get both image name and src on single onclick?

Is this possible, get both image name and src on single click of an image?

I am new to javascript and php.

 <script language="javascript" type="text/javascript">
 function SetImageName(strName)
 {
 document.getElementById("ImageName").value = strName;
 }
 </script>

 <div id="Images">

 <img src="images/image1.jpg" name="image1.jpg" onclick="SetImageName(this.name)"/></a>
 <img src="images/image2.jpg" name="image2.jpg" onclick="SetImageName(this.name)"/>

 </div><input type="hidden" value="" id="ImageName" name="ImageName"/>

Upvotes: 1

Views: 12526

Answers (3)

Dave S
Dave S

Reputation: 1423

You can get the 'src' of the image using this function:

 document.getElementById("imagename").src

So your code would be:

<script language="javascript" type="text/javascript">
    function SetImageProperties(control)
    {
        // Populate hidden fields with properties of the control
        document.getElementById("ImageName").value   = control.name;
        document.getElementById("ImageSource").value = control.src;
    }
 </script>

 <div id="Images">

 <img src="images/image1.jpg" name="image1.jpg" onclick="SetImageProperties(this)"/>
 <img src="images/image2.jpg" name="image2.jpg" onclick="SetImageProperties(this)"/>

 </div><input type="hidden" value="" id="ImageName"   name="ImageName"/>
 </div><input type="hidden" value="" id="ImageSource" name="ImageSource"/>

By passing

 this

instead of

 this.name

you are passing a reference to the whole DOM object. You can then use each property separately as shown in your modified code above.

Upvotes: 2

lolo
lolo

Reputation: 17864

When the user will click the image the function SetImageName will invoked by:

onclick="SetImageName(this)"

Meaning:

<img src="images/image1.jpg" name="image1.jpg" onclick="SetImageName(this)"/>

SetImageName Function implementation you will get the name and src of the image by image.name and image.src

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150040

Is it possible? Of course.

In your html markup:

onclick="SetImageName(this)"

And then in your JS:

function SetImageName(imgElement) {
    var theName = imgElement.name;
    var theSrc = imgElement.src;
    // etc.

That is, when you call SetImageName() pass the reference to the clicked element itself with this, rather than just its name with this.name. Then within your function you can access any and all of its properties as needed.

Upvotes: 10

Related Questions