Hello and welcome to our community! Is this your first visit?
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
    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();" />


    <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. #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,947 Times in 4,908 Posts
    Well, the best way to do it is the modern "unobtrusive JavaScript" scheme.

    <form id="Form1" runat="server">
    <asp:button id="Button1" Text="Something" AutoPostBack="False" />
    <asp:button id="Button2" Text="Whatever" AutoPostBack="False" />
    <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
    </body><!-- notice the placement of the script! just before the body's end -->
    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.
    Be yourself. No one else is as qualified.


Posting Permissions

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