Click to See Complete Forum and Search --> : this.id returns undefined -- WHY?
wood_tah
01-07-2004, 04:06 PM
Can anyone tell me why the following does not work? It returns undefined.
<a id="myID" href="javascript:alert(this.id);">test </a>
Yet, this works as it should:
<a id="myID2" href="javascript:;" onClick="alert(this.id);">test2 </a>
fredmv
01-07-2004, 04:15 PM
Welcome to the forums.
It's because you should not be using the JavaScript pesudo-protocol to execute JavaScript. It's only use is bookmarklets. It's actually executing that code as if it were in the address bar as opposed to inside of that element. Therefore, it doesn't know what element you're referring to. The most correct way to write it would be like this:<a href="#" onclick="alert(id);" id="foo">bar</a>Also note that the this keyword isn't required (http://www.webxpertz.net/forums/showthread.php3?s=&threadid=27286).
wood_tah
01-07-2004, 04:25 PM
thanks a lot, that explains it. However, I do have one follow up question to your response. I used to always use href="#", but I had always been told to use href="javascript:;" instead of href="#" b/c using the latter causes the page to scroll to the top -- is there an easy way to use href="#", but not have the page scroll to the top when clicked?
fredmv
01-07-2004, 04:30 PM
Using a hash mark is the most standard way, but, like you say, it causes the page to scroll upwards. An alternative workaround for this (without using the JavaScript pseudo-protocol) is using CSS:<a id="foo" onclick="alert(id);" style="cursor: pointer; text-decoration: underline; color: #00f;">bar</a>
ray326
01-07-2004, 10:17 PM
Return false to your onclick handler will nullify the href action.
onclick="alert(id);return false;"
fredmv
01-07-2004, 10:34 PM
Originally posted by ray326
Return false to your onclick handler will nullify the href action.You know what, Ray? You are completely correct. I can't believe I didn't remember that even though I explained it in another thread (http://forums.webdeveloper.com/showthread.php?s=&threadid=24492). I just can't believe I didn't think of that. Very good call.
wood_tah
01-08-2004, 06:29 AM
Thank you both very much..... return false; is just what I was looking for.