tags:

views:

147

answers:

3

When trying to debug what is being submitted, I wrote this.

<form action="javascript:alert(this);"
  1. Is it possible to alert what is being submitted?
  2. Here "this" denotes what?

I got object in alert box & unable to decide anything out of it. :-)

A: 

this when used in JavaScript in an HTML element's attribute is a reference of the element itself. So this in the context of your form is the form DOM object.

In other words, a rather handy use of the the keyword :)

Nick Bedford
Nope, the keyword `this` points to the element only for intrinsic event attributes (eg `"onfoo"`).
Crescent Fresh
+4  A: 

In your example this is the global window object. Try it yourself:

<form action="javascript:alert(typeof this.setTimeout);">

results in "function" (i.e. the global function). Or try:

<form action="javascript:alert(this.nodeType);">

results in undefined (i.e. it's not pointing to the form element)*.

The value of "this" inside an attribute will only ever be one of two things:

  1. the global window object
  2. the element itself

The only time this points to the element itself is when it is used inside an intrinsic event attribute (the ones that are prefixed with "on", eg "onclick", "onload", etc). These attributes are special: the browser re-scopes this to the element the event is firing on, and creates the event object (with that name) also available inside the attribute.

If the attribute is not one of the intrinsic events, "this" will be the global window object.


Footnotes:

* unless of course you happened to have a global var named "nodeType"

Crescent Fresh
+1  A: 
<form action="javascript:alert(this === window);">
<input type="submit" value="Submit">
</form>

pops up "true" when you click "Submit". It's the window object. One possibly relevant reference: https://developer.mozilla.org/en/DOM/element.addEventListener -- see the section under "The value of this within the handler".

David