DevNoob
DevNoob

Reputation: 546

Javascript getElementById can't see ASP server controls

I'm trying to get an old ASP classic project up and running as an ASP.NET webfroms solution and I'm having problems getting the javascript to connect to the ASP controls. Here is the .aspx code:

<asp:TextBox id="groupOwner2" CssClass="textbox" Runat="server" Enabled="False" TextMode="SingleLine"></asp:TextBox>

And the javascript that is supposed to manipulate it looks like this, and is trying to clear the text box:

function OnChange() {
// clear existing data

document.getElementById('<%=groupOwner2.ClientID%>').value = "";}

Originally, the the javascript control reference looked like this:

document.Form1.elements["groupOwner2"]

and that didn't work either (unsurprisingly). I've tried a number of variations on these but nothing has worked and I just get "JavaScript runtime error: Unable to set property 'value' of undefined or null reference" when the script is triggered. For the record, the script is being triggered by another control which is why the onChange() function is not mentioned in the textbox ASP code.

Any input would be appreciated!

Upvotes: 0

Views: 3495

Answers (3)

Amrik
Amrik

Reputation: 456

use ClientIDMode="Static" you can put on page directive or specifically on control you are using.

then below code works perfectly. document.getElementById('controlID');

then controlID remains same always. you do not need to use clientid.

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91724

The issue, judging by your latest comments, is that the code:

document.getElementById('<%=groupOwner2.ClientID%>').value = "";

is contained in a .js file, which (by default) is not handled by the ASP.NET engine. Even if it was, it would have no way to resolve the Client ID as it's a completely separate HTTP request.

There are two solutions:

1) Create a global variable in the .ASPX page, something like:

<script>
var GROUP_OWNER_ID = '<%=groupOwner2.ClientID%>';
</script>

Then, in your .js file you can do:

document.getElementById(GROUP_OWNER_ID).value = "";

2) Use a static ID on the web control:

<asp:TextBox id="groupOwner2" CssClass="textbox" Runat="server" Enabled="False" TextMode="SingleLine" ClientIDMode="Static"></asp:TextBox>

Note the ClientIDMode attribute. This will cause the ID to always be groupOwner2 no matter what. You can then just use:

document.getElementById('groupOwner2').value = "";

Upvotes: 4

RandomUs1r
RandomUs1r

Reputation: 4188

Try...

'<%= Page.[yourpage].FindControl("ContentPlaceHolder1").FindControl("groupOwner2").ClientID %>'

Upvotes: 0

Related Questions