Search code examples
javascriptasp.netwebformsaspx-user-control

Find Asp.net Web Forms control in script in Js (JavaScript) file


I have the following script in a Web Forms project:

function myScriptInAspxFile() {
         var obj = document.getElementById("<%= TextBox1.ClientID %>");
         if (obj) {                 
             obj.value = "My Text";                 
         }
     }

this works fine when I put the script inside the Web forms aspx file, but when I change the script to a Js (JavaScript) file the line:

var obj = document.getElementById("<%= TextBox1.ClientID %>");

The assignment returns me a null value for the obj variable. How could I find a control from a script in a Js (JavaScript) file? Greetings and thank you in advance.


Solution

  • The issue of course is that you wishing to have a hard coded text box name, and then use a external .js file. External files don't get nor enjoy server side expression processing.

    There are two approaches here:

    Use clientidMode="static" for the text box.

    Hence this:

            <asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" >
            </asp:TextBox>
    

    And now your js code becomes this:

    var obj = document.getElementById("TextBox1");
    

    Another approach?

    Place BOTH the control and JavaScript inside of a user control.

    So, say this:

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    
    <script>
        function mytest() {
            var tBox = document.getElementById('<%=TextBox1.ClientID%>')
            alert(tBox.value)
        }
    
    </script>
    

    Now, our markup becomes this:

            <asp:Button ID="Button1" runat="server" Text="Show text box value"
                OnClientClick="mytest();return false"
                />
                 <br />
    
            <uc1:MyScriptControl runat="server" id="MyScriptControl" />
    

    And the result is this:

    enter image description here

    You can also of course place some small js code stubs in the current page that calls/uses/enjoys the external .js library of code, but you thus have to "pass" the control value with smaller code stubs in the current page.

    So, say this:

       <script>
    
            function mytestlocal() {
                var obj = document.getElementById("<%= TextBox1.ClientID %>");
                mytest(obj)
            }
       </script>
    

    And thus in the external file we have this:

      function mytest(tBox) {
        alert(tBox.value)
    }
    

    So, the "very" idea of a external .js file means that external file can't have hard code controls, nor can it use or have <%=%> (server side) expressions.