简体   繁体   中英

javascript error in ASP.NET content page

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
    function Test1(w) {
        document.getElementById('<%=TextBox1.ClientID%>').style.width = w;
        return false;
    }
    Test1(10); // This line arises an error. Why ?
</script>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <input id="Button1" type="button" value="button" onclick="Test1(10)" />
</asp:Content>

I get error when the function Test1(10) is called from the script. But when it called on the click of button, it works fine. How can I call the function from the script(OR how I can access the onload() function in an ASP.NET Content Page )?

When your call to "Test1()" inside the <script> block happens, that input field is not yet part of the DOM. Thus the call to getElementById() will return null and the first line of the function will fail.

If you move the <script> block to after the text box, it should work.

edit — also you may want to explicitly append "px" to your width.

try this

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
    function Test1(w) {
        document.getElementById('<%=TextBox1.ClientID%>').style.width = w;
        return false;
    }
window.onload = function() {
    Test1(10); // This line arises an error. Why ?
}
</script>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <input id="Button1" type="button" value="button" onclick="Test1(10)" />
</asp:Content>

It's because the textbox doesn't exist when you execute Test1 in the script. You either have to place the call in a document.ready function or move it further down the page, after the textbox.

First of all you every time you want to execute javascript code, even directly from the tag ether from events you have to wait to load the dom level. So can do something like :

  <script type="text/javascript">
      window.onload =function()
      { /* code */ }
  </script>

Or execute your code in the "onload" event of the body tag: like

    <body onload="Test1(10);">
    </body>

Or if you use JQuery you can use the above :

  <script type="text/javascript">
      $(document).ready(function(){
        /* Code to execute */
      });
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM