Sherwin Flight
Sherwin Flight

Reputation: 2363

Understanding the javascript THIS keyword

I have tried to find an answer to this question by searching the web, but haven't had any luck. Most information is much more complicated then I expected this answer to be, and none actually answered this question.

In this tag:

<form method="post" action="process.php" name="processform" id="form1" onsubmit="return validate(this)">

What does "this" refer to?

If I was going to replace "this" with a hard-coded reference to the same object what would I replace it with?

Upvotes: 1

Views: 137

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173522

The this inside the "onsubmit" attribute refers to the form itself; when the validate function gets called, its first argument is that of the form's DOM element.

For example, consider this possible implementation of validate:

function validate(form)
{
    alert(form.action); // will display "process.php"
}

The good thing about using this inside the HTML (as opposed to a fixed name or ID) like this is that you don't have to refer to the form by ID or name.

Upvotes: 1

TJ VanToll
TJ VanToll

Reputation: 12704

this will refer to the form node that is being submitted. You can replace the reference with document.getElementById('form1').

Upvotes: 2

Related Questions