Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  95] [ 1]  / answers: 1 / hits: 27073  / 11 Years ago, wed, april 10, 2013, 12:00:00

I am calling method onClick function on the img and i want that image id to use further so how to access that image id



  con.innerHTML += '<table id=results width=915 border=1 style=margin:-46px 0 0 -2px;><tr><td><input id=chkbox'+j+' type=checkbox name=click_1 value=>&nbsp;'
+ str
+ '</td><td colspan=4 align=right><a href=javascript:presenter.command('viewPdf',{'path': '/images/pdf/animal/Beef/'+j+'.pdf'});><img src=images/view.png style=margin-left:250px;></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=images/email.png id='+j+' onClick=mytest()></td></tr>'+ break_line +'<img src=images/line.png style=margin-bottom:-47px;></table>';


here is the function i want to store the id of image which is j in this



     function mytest(){

var ab=document.getElementById('j');

alert(ali this is wokring fine);

}

More From » html

 Answers
44

If you insist on using inline event attributes, just do this:



onClick='mytest(this)'


...which passes a reference to the clicked element into your function:



function mytest(clickedElement) {
var theId = clickedElement.id;
}


You can then access any of the properties of the element in question. I've shown how to get the id, but you may not need the id, because if you already have a reference to the element you can obviously then work with it directly - given that it's an img, you could, for example, change its src:



clickedElement.src = someotherimg.jpg;


Note that you don't then need getElementById() at all.



UPDATE: To answer the what if? in the comment, you can setup mytest() to receive an id:



function mytest(elId) {
var ab = document.getElementById(elId);
// etc
}


And then you can call it both from an onclick handler:



onclick='mytest(this.id);'


...and directly in your code if the id is already known:



mytest('1');
mytest('2');
var someId = '3';
mytest(someId);

[#79001] Tuesday, April 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zahrafrancisr

Total Points: 176
Total Questions: 105
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;