Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

April 10, 2014

HTML5 Data Attributes and Javascript

We have an html page or an page with html elements and I want to store some data for the html elements on the client side. Prior to html5, we might be storing the data using hidden fields or query string but it's not really a clean approach and would require some javascript and matching the element and hidden field ids before it works.

To support the above use case html elements now has a new attribute "data-" and we can specify any name after the "data-". For example, we can have a data attribute like below.

March 30, 2014

I can do lot of cool things with but sometimes I don't like the idea of postbacks, specially when working on large pages. Imagine a page with a number of controls and every postback will send the controls data back and and forth and recreate the controls. So, how can I write and call methods on code-behind from aspx pages without using postbacks.

March 27, 2014

Both RegisterStartupScript and RegisterClientScriptBlock are different ways to add javascript to an aspx pages. RegisterStartupScript renders the javascript at the bottom of the html source just before the form tag closes meaning that controls and html elements defined within the page can called up by the javascript. For example, if I have a span or div element within the page, I can change the color or any other style properties using RegisterStartupScript and the new style will appear straight way.

March 18, 2014

I have got an page with a number of anchor links pointing to different sections of the page. Now I problem is that since the page is an page and has buttons and / or possibly other controls that performs postbacks - the anchor position is lost during postbacks. Now this can be an irritating problem as I don't want my users having to click on the anchor link or to scroll to that location. actually have an option to persist scroll locations during postbacks but though it works it has issues like bookmarking will not work.

To avoid the above problem, I have a simple solution that will persist the anchor and it requires the use of javascript and a hidden field to store the location of the anchor. I have couple of javascript functions - one that updates the anchor location in the hidden field and another one that set the hash property of window.location object to the value stored in the hidden field. The code is self explanatory, so I won't go into the details of explaining it. One thing to note is that I have a set the OnClientClick property of the button (or any control that postbacks) to javascript method that updates the hash / anchor location in the hidden field. Here is the code on how to achieve this.

  1. <asp:Button ID="b1" runat="server" OnClientClick="UpdateHash()" OnClick="b1_Click" />
  2. <asp:HiddenField ID="hf1" runat="server" />


  1.     <script type="text/javascript" src=""></script>
  2. <script type="text/javascript">
  3.     function UpdateHash() {
  4.         $("#hf1").val(window.location.hash);
  5.     }
  7.     function LoadHash() {
  8.         var hash = $("#hf1").val();
  9.         if (hash != "" && hash != "undefined") {
  10.             window.location.hash = hash;
  11.         }
  12.     }
  14.     window.onload = LoadHash;
  15. </script>

January 5, 2014

Add CSS File using Javascript

Let's imagine a situation where we want to load a css file using javascript. This could be, for example, a situation where we want to add a new stylesheet based on an user action. To do this using javascript is similar to adding a new element in the html file using javascript. Here's the source code on how to achieve this.

December 12, 2013

There is not a lot of differences between window's onload and body onload events except that window's onload event fires at start whereas body's onload event fires once all content is downloaded. So, in case, we need to find an element and update style or content, etc to it, then, body onload is the way to go. Whereas if it does not matter - then we can use either window's onload or body onload event. Below is an example html source code to check when each of the events is fired.

September 11, 2013

Dynamically loading JavaScript files

This post is about a situation where one might need to dynamically select and load a javascript file based on a logic. For example, if you have deployed a site but accessing it from multiple domains / sub-domains but you want to load correct analytics code, etc. This might sound silly at the first instance, but reasonable situation are when the same site is deployed to be accessed from multiple countries and they have urls like and .

So, in this example, I will show how to dynamically load the correct analytics files based on the domain name. At first, there is a function  - CheckUrl() - that checks the url and based on the url calls the LoadAnalytics() function passing the correct script files. One thing to note here is that the analytics script files are saved in separate javascript files.

The LoadAnalytics() function creates a script element, sets the source  property and appends the script element to body section of the page. The CheckUrl() function also needs to be called from the onload event of the page. Here is the source code for the page.

Dynamic JavaScript
  1. function CheckUrl()
  2. {
  3.     var url = window.location.href.toLowerCase();
  4.     var au = "";
  5.     var uk = ""
  6.     if(url.indexOf(au) >= 0)
  7.     {        
  8.         LoadAnalytics("js/au.js");
  9.     }
  11.     else if(url.indexOf(uk) >= 0)
  12.     {
  13.         LoadAnalytics("js/uk.js");
  14.     }
  15. }
  18. function LoadAnalytics(scriptLocation)
  19. {
  20.     var script = document.createElement("script");
  21.     script.type  = "text/javascript";
  22.     script.src   = scriptLocation;
  23.     document.body.appendChild(script);
  24. }

To verify if it is working, you can check the source code but the analytics code will not show up in the page. To verify if it works, place an alert statement in the script file and you will see the alert works. You can also use the Network tab in Page Inspector in Google Chrome to check if the script has loaded.
To verify further, you will need to check if the tracking data comes in your analytics software.

August 28, 2012

The setInterval() method is part of the window object that either calls a function at some specified time interval. It can also evaluate an expression. The interval is specified in milliseconds.

The setInterval() method, can for example, be used to display a timer on a page. The function called with this method will continue to run until the clearInterval() method is called.

An example of the setInterval() method is below.

<script type="text/javascript">
interval = window.self.setInterval(function () { ShowTime() }, 1000);
function ShowTime() {
var time = new Date().toTimeString();
document.getElementById("id1").innerHTML = time;
<span id="id1">Date will appear here</span>


An example of how to stop the setInterval() using clearInterval() method is below. Note that, the ID set by setInterval() method is used within the clearInterval() method to stop the timer.

<button id="b1" onclick="window.clearInterval(interval)">Stop</button>

On the other hand, the setTimeout() method which is part of the Window object can be used to run a function or expression after a specified time. The syntax for this method is similar to setInterval() method. This function can be used, for example, to display some message to the end user after a specified period of time. The message, for example, could be a call to action for a user who has spent at 1 minute on the page, etc.

An example of the setTimeout() method works is below.

var interval2 = window.self.setTimeout(function () { ShowAfterSomeTime() }, 10000);
function ShowAfterSomeTime() {
var time = new Date().toTimeString();
document.getElementById("id2").innerHTML = time;

The setTimeout() method's timer can be cleared by using the clearTimeout() method. This might be useful when, for example, a message needs to be displayed after a particular time but due to user's actions, we choose not to display the message, etc.

An example of how to use the clearTimeout() method is below. Note that, the ID set by setTimeout() method needs to be passed into clearTimeout() method for it work.

<input type="button" value="Stop count!" onclick="stopCount()" />
script type="text/javascript">

June 5, 2011

Access anchor link from code-behind

Html anchor links are a way to navigate within a page. The anchor can be considered as a bookmark within a page, which when clicked takes the user to that section of a page. An anchor to a certain section of a page can be set in the following way.

  1. <a name=”anchor”></a><div>content</div>

The name attribute of the “a” element determines the anchor / bookmark to the page. The anchor can be accessed by setting the link like below.

  1. <a href=”#anchor”>Anchor</a>

However, the anchor link is a client side thing and cannot be accessed from server-side. In this post, I am going to show how the anchor link can be accessed from server-side using hidden field and javascript. The following is the code for the aspx page.

aspx page
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.     <a name="anchor"></a>
  5.     <div>Some content <a href="#anchor" onclick="SetUrl('anchor')">click here</a></div>
  6.     <asp:HiddenField ID="HF1" runat="server" />
  7.     <asp:Button ID="B1" runat="server" Text="Check Anchor" OnClick="GetAnchor" />
  8.     <asp:Literal ID="L1" runat="server"></asp:Literal>
  9.     </div>
  10.     <script type="text/javascript">
  11.         SetUrl("");
  12.     </script>
  13.     </form>
  14. </body>

The page is simple, contains a HiddenField, Button and Literal control to display the anchor, if any. At the bottom of the page, before the closing form tag is a javascript method, SetUrl(“”) that sets the anchor in the hidden field. The code for javascript method is below.

JavaScript code
  1. <script type="text/javascript">
  2.     function SetUrl(val) {
  3.         if (val == "" && location.href.indexOf("#") > -1) {
  4.             document.getElementById('<%= HF1.ClientID %>').value = location.href; //set value of HiddenField
  5.         }
  6.         else if (val == "" && location.href.indexOf("#") == -1) {
  7.             document.getElementById('<%= HF1.ClientID %>').value = "";
  8.         }
  9.         else {
  10.             document.getElementById('<%= HF1.ClientID %>').value = val;
  11.         }
  12.         alert(val);
  13.     }    
  14. </script>

The javascript method, checks if there is a value for the anchor when the link is clicked. If not and if it does not contain the “#” character in the url, it does not set the value of the anchor in the HiddenField. Otherwise, it either sets the value when clicked or sets the url if it contains “#” character.

Once the HiddenField value is set, the value can be accessed from the server side. In this example, when the button is clicked, the value is obtained and set as the Text property of the Literal control. Here is the code for Button click event.

Button click event
  1.     protected void GetAnchor(object sender, EventArgs e)
  2.     {
  3.         string anchor = HF1.Value;//get url from hidden field
  4.         if (anchor.Contains("#"))//check if it an anchor
  5.         {
  6.             string[] list = anchor.Split(new char[] { '#' });
  7.             L1.Text = "anchor name is :" + list[1];
  8.         }
  9.         else if (anchor != "")
  10.             L1.Text = anchor;
  11.         else
  12.             L1.Text = string.Empty;
  13.     }
  14. }

The code finds the value of the HiddenField and displays it in the Literal control.

February 23, 2011

There are few different ways to redirect a web page to another page in Redirection can be achieved by using JavaScript, meta tags and by using methods as well. In this blog post, I will show how to setup redirection using each method and what are the pros and cons of it.


Adding redirect using JavaScript involves only one line of code. The following is the code added in a content page.

Redirect using JavaScript
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Redirection.aspx.cs" Inherits="WebApplication1.Redirection" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3.    <script type="text/javascript">
  4.     window.location = "default.aspx";
  5. </script>
  7. </asp:Content>
  8. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  9. </asp:Content>

When the page is run, content from the master page is loaded  first and then the page redirects to new page using HTTP status code of 200. The HttpFox report from FireFox is below.


As can be seen from Http watch report, the page is loaded first and then the page is redirected. The problem with this approach is that redirect would not work if JavaScript is disabled by the user and also search engines are fooled to think that the page is ok when it is not.

META Tags:

Secondly, meta tags can be used to redirect pages. An example code is below.

Redirect using Meta tags
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Redirection.aspx.cs" Inherits="WebApplication1.Redirection" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  3. <meta http-equiv="refresh" content="0;url=default.aspx" />
  4. </asp:Content>
  5. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  6. </asp:Content>

The Http watch report is below.


As can be seen, the css file is loaded first and then the page redirects using Http status code of 200. Similar to the JavaScript approach,  the problems are that someone can stops meta refreshes from browser settings and search engines are fooled to think that the page is valid.

ASP.Net Redirect

In, pages can be redirected using 2 methods. The first method is by using the method – Response.Redirect(string url). Example code is below.

Response.Redirect(string url)
  1. namespace WebApplication1
  2. {
  3.     public partial class Redirection : System.Web.UI.Page
  4.     {
  5.         protected void Page_Load(object sender, EventArgs e)
  6.         {
  7.             Response.Redirect("default.aspx");
  8.         }
  9.     }
  10. }

Http watch report is below.


As can be seen from the code, the page is redirected straight way using http status code of 302. This is a server side redirect and cannot be controlled by the browser. Well, a user may stop loading the page by clicking the Stop button in the browser but I am not counting that.

The main drawback of this approach is that it uses a 302 redirect. This means it is a temporary redirect which is bad for SEO.

Previously, redirect could be used differently to allow 301 redirect. 301 http status codes means the page has moved permanently and is search engine friendly. Here is a sample code. 301 redirect
  1. namespace WebApplication1
  2. {
  3.     public partial class Redirection : System.Web.UI.Page
  4.     {
  5.         protected void Page_Load(object sender, EventArgs e)
  6.         {
  7.             Response.Status = "301 Moved Permanently";
  8.             Response.AddHeader("Location", "default.aspx");
  9.         }
  10.     }
  11. }

Http watch report is below.


In the new release of .NET 4.0, Microsoft has added a new method Response.RedirectPermanent(string url). This method also allows for 301 redirects. Sample code is below.

RedirectPermanent(string url)
  1. namespace WebApplication1
  2. {
  3.     public partial class Redirection : System.Web.UI.Page
  4.     {
  5.         protected void Page_Load(object sender, EventArgs e)
  6.         {
  7.             Response.RedirectPermanent("default.aspx");
  8.         }
  9.     }
  10. }

The http watch report produced when the page is run is below.


January 1, 2011

In this post, I have demonstrated how to calculate the number of words using both JavaScript and C# code and also how to restrict a TextArea or a multiline TextBox control to contain the specified number of words. One of the challenge in writing this article is to determine what a word is. For the purpose of this post, I have considered any text to be a word that is separated by a space. The words may contain symbols but must contain alphabets. For example, work’s is a word but ;’; is not.

On aspx page, a multiline TextBox control and a span element is first declared. The text to be manipulated will be obtained from the TextBox and the span will display the status. The code is below.

  1. <asp:TextBox ID="T2" runat="server" TextMode="MultiLine" Rows="3" onkeyup="WordCount()"></asp:TextBox>
  2. <span id="T2Status" style="color:Red;">5 word(s) remaining.</span>

The TextBox contain a KeyUp event. This is a JavaScript event that checks the number of words entered in the TextBox control and updates the status in the span element. The JavaScript code is below.

JavaScript - TextBox max words
  1. <script type="text/javascript">
  2.     function WordCount() {
  3.         var text = document.getElementById('<%= T2.ClientID %>').value;
  4.         var list = text.split(" ");
  6.         var x; var upper; var lower;
  7.         var count = 0;
  8.         var max = 5;
  10.         //Use the following to count the number of words
  11.         /*for (x in list) {
  12.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  13.                 count = count +1;
  14.             }
  15.         }*/
  17.         var val = "";
  19.         for (x in list) {
  20.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  21.                 if (count +1 <= max) {
  22.                     count = count + 1;
  23.                     val += list[x];
  24.                     //alert("val: " + val + " list: " + list[x]);
  25.                 }
  26.             }
  27.             else {
  28.                 if (count <= max) {
  29.                     val += list[x];
  30.                     //alert("val: " + val + " list: " + list[x]);
  31.                 }
  32.             }
  33.             if (x != list.length -1) {
  34.                 val += " ";
  35.             }
  36.         }
  38.         document.getElementById('<%= T2.ClientID %>').value = val;
  39.         document.getElementById('T2Status').innerHTML = max - count + " words remaining";
  40.     }
  42. </script>

In JavaScript code, I am first getting the string from the TextBox and then splitting it into an array. Then, I am converting each string in the array into both upper and lower case. Then, I am comparing the converted strings. If the string match, it’s a word, otherwise, not. At the same time, I am creating another string based on the values in the array till it hits the max number of words. This string is then used to populate the TextBox.

The same can be achieved using C# code but this will cause unnecessary postbacks to the server. However, it is advisable to check the data using C# to avoid a user submitting the data from a browser with JavaScript disabled.

I have written two methods – one to do a word count and want to limit the string to a maximum number of words. In this first method to do a word count, I have broken the string into a string array using space - “ “ - as the delimiter. Then, I have check if a particular string on the array contains an English letter. If it does, the counter is updated. The code for this method is below.

C# - WordCount() method
  1. private int WordCount(string s)
  2. {
  3.     int c = 0;
  4.     string[] split = {" "};
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  13.     string val = string.Empty;
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.             c++;                             
  19.     }
  21.     return c;
  22. }

In the next method, I have reconstructed a string to limit it to maximum number of words specified. It uses the same logic as to count the number of words. A new string is created based on the values in the string array. The code for the method is below.

C# - String, max words
  1. private string MaxWord(string s, int max)
  2. {
  3.     int c = 0;
  4.     string[] split = { " " };
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  13.     string val = string.Empty;
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.                 c++;
  19.         if (c <= max)
  20.             val += list[i] + " ";
  21.     }
  23.     return val;              
  24. }

December 29, 2010

It is a common scenario to have a textarea element  or multiline TextBox control in a html / page and the challenge is to limit the number of characters that can be entered and to display the remaining number of characters that can be entered. The textarea unlike the TextBox control does not support the maxlength property and thus cannot be limited. The solution is to use javascript to limit the number of characters.

In this example, I have added a TextBox control and added the onkeyup event for the control. The code for the page is below.

  1. <asp:TextBox ID="T1" runat="server" TextMode="MultiLine" Rows="3" onkeyup="T1_KeyUp()"></asp:TextBox>
  2. <span id="T1Status" style="color:Red;">50 character(s) remaining.</span>

The span element in the page will display the number of remaining characters that can be entered in the TextBox.

The JavaScript code is below. The code sets the max length of the TextBox to 50 characters.

JavaScript function
  1. <script type="text/javascript">
  2.     function T1_KeyUp() {
  3.         var text = document.getElementById('<%= T1.ClientID %>').value;
  4.         var len = text.length;
  5.         var max = 50;
  6.         if (len > max) {
  7.             text = text.substring(0, max);
  8.             len = 50;
  9.             document.getElementById('<%= T1.ClientID %>').value = text;
  10.         }
  11.         document.getElementById('T1Status').innerHTML = max - len + " character(s) remaining.";
  13.     }
  14. </script>

Server side could also be used for this but it will cause unnecessary postbacks to the server. However, the actual text entered should be validated from the server end as JavaScript can be easily disabled by a user.

August 22, 2009

At times, we may need to pass data from client to control. For example, we can ask the the user for a name and display the users name in a Label control. In this code snippet, I will use javascript to prompt the user for his name and display it a Label control.

Here, is the Label control.
    <asp:Label ID="LabelScript" runat="server" Text=""></asp:Label>

Here, is the javascript function to prompt the user for his name.

    <script type="text/javascript">
        function promptLabel() {
            document.getElementById('<%= LabelScript.ClientID %>').innerHTML =
            window.prompt("Please enter your name.");       

The last thing is to call the method when the page loads. This is done by setting the onload attribute of the html body tag to the function's name.
    <body onload="promptLabel()">

When the page is loaded, the page displays a prompt asking for the name. When the user enters his/her name, and presses the ok button, the Label control in the page displays his name.

August 20, 2009

To check if a TextBox value has changed or not, we can use "OnTextChanged" event of the TextBox. This will require setting the AutoPostBack property to true and will fire a postback to the server each time the TextBox changes. Therefore, it will decrease performance of the page adding little value.

Alternatively, we can use javascript to check if the Text property of a TextBox control has changed or not. In this example, I will create a TextBox and Label control and when the TextBox changes, the Label will populate with the Text in the TextBox.

Here is the declaration of the Label and TextBox controls.

<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

I will add the javascript to the TextBox in the Page_Load method.
TextBox3.Attributes.Add("onchange", "TextBoxChange()");

This will add an "onchange" attribute and "TextBoxChange()" will be called when the text changes in the TextBox.

In the javascript function, I will find the Text of the TextBox control and assign it to the innerHTML property of the Label control. Here is the code,

function TextBoxChange()
        document.getElementById('<%= Label2.ClientID %>').innerHTML =
            document.getElementById('<%= TextBox3.ClientID %>').value;

When the page is run, and then TextBox text is changes, the text of the Label control updated. Checking if the text property of a control has changed or not using javascript is more efficient since it avoids unnecessary postbacks to the server.

July 14, 2009

At times, the built in validation controls are not sufficient to perform a validation for a particular business rules. In this situation, we can use the CustomValidator control and use either or both javascript and server side validation. Here, I will show how to use javascript to perform client-side validation using the CustomValidator control.

At first, I will create a normal page and then add a TextBox control whose content will be validated, a Button control that will simply perform a postback and a CustomValidator control to validate the TextBox. Here is the code for the page,

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:CustomValidator ID="CV1" runat="server" ControlToValidate="TextBox1" ErrorMessage="invalid" Display="Static" ClientValidationFunction="CheckTextBox"></asp:CustomValidator>
        <asp:Button ID="Button1" runat="server" Text="Click" />

The CustomValidator control looks similar to other validation control. It has an extra attribute ClientValidationFunction that is set to the javascript function name "CheckTextBox".

The javascript function checks for the length of the string data that is passed from the TextBox1 control. If it is not between 6 and 10 characters, then it returns an error. Here is the javascript function.

function CheckTextBox(source, arguments)
        var data = arguments.Value.split('');
        arguments.IsValid = false;//set IsValid property to false

        if (data.length >= 6 && data.length <= 10) //check if the content is between 6 and 10 characters
            arguments.IsValid = true;

The function must have the signature FunctionName(source, arguments). The arguments parameter has a property called "IsValid" that determines whether the page is valid or not. In the function, we start by setting the IsValid property to false. If the logic succeeds, we set the IsValid property to true.

When the page is run and we enter text in the TextBox1 control and click the Button - the javascript code is called and if the logic succeeds - the page postbacks successfully. Otherwise, the ErrorMessage is displayed and the page does not postback.

July 12, 2009

I am going to show how to create dynamic Button controls, add event handlers, javascript and then add it to the page. To do so, I will create a page with no controls in it. From the code-behind, I will add the Buttons.  Here is the code for the Page_Load event.

   protected void Page_Load(object sender, EventArgs e)
            form1.Controls.Add(GetButton("Button1", "Click"));
            form1.Controls.Add(GetButton("Button2", "Click again"));

As can be seen, I am adding controls to the form element by calling the method GetButton. The GetButton method takes two parameters of type string. Here, is the code for the GetButton method.

   private Button GetButton(string id, string name)
            Button b = new Button();
            b.Text = name;
            b.ID = id;
            b.Click += new EventHandler(Button_Click);
            b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
            return b;

GetButton is a private method taking two arguments id and name of type string. In the method, I am creating a Button object and assigning the Text and ID attributes using the arguments passed. Then, I am adding a Click event and creating a new EventHandler Button_Click. Then, I am adding a OnClientCllick attribute and passing a javascript function name "ButtonClick" and passing the ClientID of the Button control as a parameter. Lastly, the methos is returning the Button control.

As can be seen, the GetButton method has an EventHandler Button_Click which has not been defined. Here is the code for the Button1_Click event.

    protected void Button_Click(object sender, EventArgs e)
            ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
            Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");

In this method, I am registering a javascript and passing an alert to test if the Button is clicked. Also, I am writing the ID of the Button that has been clicked.

From the GetButton method, I am also assigning a javascript function "ButtonClick" to OnClientClick property. This method is defined on the main page as follows.

     <script type="text/javascript">
        function ButtonClick(buttonId) {
            alert("Button " + buttonId + " clicked from javascript");

The function does an alert with the id of the Button in it.
When the page is run, two Button controls are added to the page with text "Click" and " Click Again". When the buttons are clicked, javascript alerts can be seen on the page and an output is displayed with date and time and the id of the button that was clicked.


July 1, 2009

Resizable DropDownList

In this example, I will create a resizable DropDownList. The DropDownList control has a width property that is set to a fixed width. Using javascript, I am modifying the width of the DropDownList.

Inside the form tag,

<form id="form1" runat="server">   
    <asp:DropDownList ID="DropDownList1" runat="server" Width="50px">

I am adding a DropDownList with fixed width. Then in the Page_Load method,

protected void Page_Load(object sender, EventArgs e)
        DropDownList1.Attributes.Add("onmouseover", "ddlMouseOver()");
        DropDownList1.Attributes.Add("onmouseout", "ddlMouseOut()");

I am adding 2 attributes "onmouseover" and "onmouseout" javascript functions to the DropDownList.
In the actual javascript, I am changing the width of the control accordingly.

<script type="text/javascript">
    function ddlMouseOver()
        document.getElementById("<%= DropDownList1.ClientID %>").style.width = "200px";
    function ddlMouseOut()
        document.getElementById("<%= DropDownList1.ClientID %>").style.width = "50px";

June 25, 2009

The validation controls in is capable of displaying an error message but it does not display success message. In this example, I will create a TextBox control, add a RequiredFieldValidator and then a custom javascript function to display a success message.

Here is the code for the page.

<form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <span id="successSpan" style="color:Red;"></span>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 is required" ControlToValidate="TextBox1"></asp:RequiredFieldValidator><br />       
        <asp:Button ID="Button1" runat="server" Text="Button" />

In the code for the page, there is a TextBox control, Button control, RequiredFieldValidator to validate the TextBox and a html span element that will contain the text for the success message.

In the Page_Load method for the page, I am adding an "onblur" attribute to the TextBox control.

protected void Page_Load(object sender, EventArgs e)
            TextBox1.Attributes.Add("onblur", "showSuccess()");

This attribute will fire the showSuccess() function when the TextBox control loses focus. Here is the javascript code,

<script type="text/javascript">
        function showSuccess() {
            if (document.getElementById("<%= TextBox1.ClientID %>").value == "") {
                document.getElementById("successSpan").innerHTML = "";
                document.getElementById("successSpan").innerHTML = "Success";

The function checks if the TextBox control has any text or not. If not, it resets the span element's text or otherwise displays the text, "Success", in the span element.

June 20, 2009

In this example, I will get the TimeZone offset using javascript and then display the value in a textbox on a Button click. I will also display the local time in in GMT. The code for the page is below.

<head runat="server">
    <script type="text/javascript">
        function GetClientUTC() {
            var now = new Date()
            var offset = now.getTimezoneOffset();
            document.getElementById("HiddenFieldOffset").value = offset;
            document.getElementById("HiddenFieldGmt").value = offset / 60;
<body onload="GetClientUTC()">
    <form id="form1" runat="server">
    Local time in GMT:
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:HiddenField ID="HiddenFieldOffset" runat="server" />
        <asp:HiddenField ID="HiddenFieldGmt" runat="server" />

In the page, I have a TextBox, a Button, a Label and 2 HiddenField controls. The javascript function finds the offset value and the GMT time and sets the value of the HiddenFields.

In code-behind, the Button onclick handler finds the HiddenFields' values and set the TextBox and Label controls. The code is here.

protected void Button1_Click(object sender, EventArgs e)
            TextBox1.Text = HiddenFieldOffset.Value;
            Label1.Text = HiddenFieldGmt.Value;

Reference: Shahed Kazi at