Search code examples
asp.netjavascriptuser-controlsascx

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


Solution

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