Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Access ASP.NET Server Controls in JavaScript Files

0.00/5 (No votes)
5 Nov 2013 1  
How to acccess ASP.NET server controls in JavaScript files

Introduction

This tip describes the way to access the ASP.NET server controls in JavaScript files. This facilitates to move the JavaScript code to a separate JS file.

Using the Code

Follow the steps given below:

  1. Create an aspx file and create an object that will be used to contain all the control ids that you need to access from JavaScript file. Adjust the path and name for the jquery min.js accordingly:
    <script src="../js/jquery.ui-1.8.6.min.js" 
    type="text/javascript"></script>
    //Initialize variable to be used in the RecurrentAppointment.js
            var RecurrentRelatedIDs = {};
  2. Initialize the control in $(document.ready) / $(function) so this control can be accessed from js file and call the js file function:
    $(function () {
                //Initialiaze the controls for RecurrentAppointment.js
                RecurrentRelatedIDs = {
                    txtAppointmentDateID: '<%= txtAppointmentDate.ClientID%>'
                  , txtStartsOnDateID: '<%= txtStartsOnDate.ClientID%>'  
    };
    FunctionsToRunAtDocumentReady();
    }); 
  3. Create the js file and add 'function FunctionsToRunAtDocumentReady()' in the js file. This function is called from main page after the control id object is initialized. The js file can access the server controls via the object created earlier:
    function FunctionsToRunAtDocumentReady(){
    RecurrentRelatedIDs.txtAppointmentDateID = 1; 
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here