views:

164

answers:

1

Hi,

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 occured.

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 javscript function itself.

Your help is highly appreciated.

+4  A: 

Try:

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

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

Aaron Digulla
this is the easiest way to achieve a reference to the element that the event was raised on
Russ Cam
Yep, that's the best way. Using direct reference instead of ID.
terR0Q
But my friends, i am not able to get the control id using document.getElementById(this.id);or how should i get the id in JS function?
IrfanRaza
@IrfanRaza: Which ID are you talking about? `this` is the same thing that `getElementById()` returns, so you don't have to call it again.
Aaron Digulla