netseng
netseng

Reputation: 2286

How to Access ASP control located in a user control via JavaScript

Hi All,

I'm designing a user control, briefly it contains an asp:hiddenfield control, i'm going to access it via JavaScript function like this

function doAnyThing
{
    var myVar = document.getElementById("myHiddenFiled");
}

but when I trace my code I found myVar assigned to null, does it matter

document.getElementById()

method is used in user control file (.ascx) or in regular (.aspx) file, taking into consideration it works in (.aspx) file correctly

Upvotes: 1

Views: 13866

Answers (2)

tanathos
tanathos

Reputation: 5606

You had to set by ClientID the final id of your control, that will depend by the structure of your page. Try this:

function doAnyThing
{
    var myVar = document.getElementById("<%= yourControlServerID.ClientID %>");
}

Obviously this function need to be placed in the .aspx file. I suggest you to switch to use a framework like jQuery, that allows you to retrieve controls by more sofisticate selectors. This case will be solved by:

$("[id$=yourControlServerID]");

and you can place your javascript code even in an external .js file.

Upvotes: 9

balexandre
balexandre

Reputation: 75083

to simplify you can use either:

JQuery

$("<%= yourControlServerID.ClientID %>"). ....

ASP.NET JavaScript annotation:

var myVar = $get("<%= yourControlServerID.ClientID %>");

the ASP.NET JavaScript annotation code is the same as:

var myVar = document.getElementById("<%= yourControlServerID.ClientID %>")

Upvotes: 2

Related Questions