Link to home
Start Free TrialLog in
Avatar of dotnet22
dotnet22

asked on

passing textbox id in javascript

I'm doing the following on the server side

oButton.Attributes.Add("onclick", "MyFunction(this.ID)")


on the client side I have the following javascript function

MyFunction(theId)
{

alert(theId);

}

But I get  an error Object expected. How can I pass the textboxes id in dynamicall because they are part of a user control and the names are dynamic. Thanks.

Avatar of Sammy
Sammy
Flag of Canada image

<script type="text/javascript">
MyFunction(myId){
alert(document.getElementById(myId));
}
</script">
HTH
Avatar of Sam_Jayander
Sam_Jayander

Hi,

use,
oButton.Attributes.Add("onclick", "MyFunction(this.id)")

while accessing the id-property in javascript you must use "id" and not "ID".

Regards,
--Sam.
ASKER CERTIFIED SOLUTION
Avatar of bele04
bele04

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oButon.ID is not a safe value as it gets chaned by the compiler when the control is contained with another control. Use oButton.ClientID rather.

Better still is to use the following:

Code:
oButton.Attributes.Add("onclick", "MyFunction(this)")

or if you are using asp.net 2: <asp:button runat="server" id="btn" OnClientClick="javascript:MyFunction(this);" />

HTML:
<script type="text/javascript">
function MyFunction(obj)
{
  alert("Object id: " + obj.id) // will show you the id of the button that was clicked; alternatively "obj" is the button object to be manipulated.
}
</script>