Javascript – Getting source control id in JavaScript function

asp.netjavascript

I have taken three textboxes over aspx page. A JavaScript function is associated with these textboxes as:

TextBox1.Attributes.Add("onkeypress","MyFunction()");

TextBox2.Attributes.Add("onkeypress","MyFunction()");

TextBox3.Attributes.Add("onkeypress","MyFunction()");

The MyFunction() is defined within a JavaScript file.

What I want is to get the control id of the textbox on which the function is associated within the JavaScript function itself. That is, the JavaScript function should look like this:

function MyFunction() {
   var myControl = ?;
   alert("Key press event occured in "+myControl.ID);
}

I need the value of ?. What should I write there so that I could get the control id, i.e. TextBox1, TextBox2, or TextBox3 on which the event occurred?

I know that <% =TextBox1.ClientID %> will provide the id of TextBox1 on client. But I think as I am attaching the onkeypress event with the textbox I should get the source control id within JavaScript function itself.

Best Answer

Try:

TextBox1.Attributes.Add("onkeypress","MyFunction(this)");

JS will put the reference to the widget into this when the code for onkeypress is evaluated.