Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2010
    Posts
    46
    Thanks
    1
    Thanked 1 Time in 1 Post

    Javascript in ASP.net

    How do you run a Javascript program in ASP.net 4.0 controls.

    The old way:
    <input id="Button1" type="button" onclick="program();" />

    or

    <body onload="program();">

    ASP.net controls do not accept onclick or onload.

    How do you run a Javascript in ASP.net on any control?

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Well, the best way to do it is the modern "unobtrusive JavaScript" scheme.

    Code:
    <form id="Form1" runat="server">
    <asp:button id="Button1" Text="Something" AutoPostBack="False" />
    <asp:button id="Button2" Text="Whatever" AutoPostBack="False" />
    ...
    </form>
    
    <script type="text/javascript">
    (
      function( ) /* anonymous master function */
      { 
          // form not needed for this example, but this is what you could use:
          var form = document.getElementById("<%=Form1.clientID %>");
    
          // for the buttons:
          document.getElementById("<%=Button1.clientID %>").onclick = program;
          document.getElementById("<%=Button2.clientID %>").onclick = program;
    
          function program( ) 
          { 
              // inside this function, you can refer to the button via this.  Example:
              var buttonValue = this.value; // gets the ASP.Net TEXT property 
              ...
          }
    
      } // end of master anonymous function
    )(); // self-invoke anonymous function
    </script>
    </body><!-- notice the placement of the script! just before the body's end -->
    </html>
    CAUTION: If the button is set to do an autopostback, then you can't just assign to the onclick property, as shown. Instead, you would need to use attachEvent (for older MSIE) and/or addEventListener (for newer MSIE and all other browsers). If you do just assign to onclick, as shown above, that would disconnect the autopostback and *ONLY* execute your client-side JS code.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •