Monday, November 1, 2010

Create Radio Button Dynamically like gmail User ID suggestion

Introduction: In my project I face a problem that generate user id dynamically and show it in a radio button list. For example when create a new gmail account user first time supply user id and if the user id is not available the gmail show some user id as suggestion. After some google i found how to generate radio button dynamically but this was not sufficient for me. So I decide to write some thing so that people may get help from my writing.

Procedure: First I create a page that contain
                 1. A text box which is used to supply the user ID.
                 2. A button that is used to check availability.
If the user id is not available then a radio button group with suggested user id will show below the text box. This is the scenario. Let see how can we do that with javascript and asp.Net.

Step1: Add the aspx page that contain the text box and the button. The script of the page is as follows:
 
<%@ Page Title="" Language="C#" MasterPageFile="~/Master Pages/LogedIn.Master" AutoEventWireup="true" CodeBehind="RadioButtonTest.aspx.cs" Inherits="JqueryTest.RadioButtonTest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <div>
        User ID:
        <asp:TextBox ID = "txtUserID" runat = "server" />
        <input id="btnCheckID" value="Check availability"  type="button" onclick="usernameChecker();" />
        <span id="spanAvailability"></span>
      
    </div>
    <div id="divRadiolist">
    </div>
   
</asp:Content>

Step2: Now add the necessary javascript code below the button and span. The javascript code is given below:
<script type="text/javascript">
            var usernameCheckerTimer;

            var spanAvailability = document.getElementById("spanAvailability");
            var dvSuggest = document.getElementById("divRadiolist");
            function usernameChecker() {
                var username1 = document.getElementById("ctl00_ContentPlaceHolder1_txtUserID");
                var username = username1.value;
                clearTimeout(usernameCheckerTimer);
              
                    spanAvailability.innerHTML = "<span style='color: #ccc;'>checking...</span>";
                    usernameCheckerTimer = setTimeout("checkUsernameUsage('" + username + "');", 750);
              }

            function checkUsernameUsage(username) {
                // initiate the ajax pagemethod call
                // upon completion, the OnSucceded callback will be executed
                PageMethods.IsUserAvailable(username, OnSucceeded);
            }

            // Callback function invoked on successful completion of the page method.
            function OnSucceeded(result, userContext, methodName) {
                if (methodName == "IsUserAvailable") {

                    if (result == "0") {
                        spanAvailability.innerHTML = "<span style='color: DarkGreen;'>Available</span>";
                        divRadiolist.style.display = "none";
                    }
                    else {
                        spanAvailability.innerHTML = "<span style='color: Red;'>Unavailable</span>";
                        divRadiolist.style.visibility = "visible";
                        /** This code is for show the suggesstion.Added by zafor 2010/10/27  **/
                        var checkAvailable = result.toString().split('|');
                        //Two dimentional array hold suggested user id
                        var arrData = [["0", checkAvailable[0]], ["1", checkAvailable[1]], ["2", checkAvailable[2]], ["3", checkAvailable[3]]];

                        //read div which show available user id
                        var radioDiv = document.getElementById("divRadiolist");
                        var username1 = document.getElementById("ctl00_ContentPlaceHolder1_txtUserID");
                        var username = username1.value;

                        radioDiv.innerHTML = "<p style='color: Red;'>" + username + " is not available but the followings are</p>";
                        //This for loop used to create the radio list
                        for (var i = 0; i < arrData.length; i++) {
                            var createRadioItem = document.createElement("input");
                            createRadioItem.type = "radio";
                            createRadioItem.name = "radioButtonGroup";
                            createRadioItem.id = "radioItem_" + i;

                            createRadioItem.value = arrData[i][1]
                            createRadioItem.setAttribute("onclick", "JavaScript:return getSelectedRadioValue()");

                            var objTextNode = document.createTextNode(" " + arrData[i][1]);

                            var createLabel = document.createElement("label");
                            createLabel.htmlFor = createRadioItem.id;
                            createLabel.appendChild(createRadioItem);
                            createLabel.appendChild(objTextNode);

                            var createBreak = document.createElement("br");

                            radioDiv.appendChild(createLabel);
                            radioDiv.appendChild(createBreak);
                        };

                        /** End the suggestion code  **/
                        divRadiolist.style.display = "block";
                    }
                }
            }
        </script>

  <%-- This javascript function is for select suggesstion. Added by zafor 2010/10/27--%>
  <script type="text/javascript">
          function getSelectedRadioValue() {
                var node = document.getElementsByName('radioButtonGroup');

                for (var i = 0; i < node.length; i++) {
                    if (node[i].checked) {
                        var rad_val = node[i].value;
                    }
                }
                var userID = document.getElementById('ctl00_ContentPlaceHolder1_txtUserID');
                userID.value = rad_val;
            }
 </script>

We use Ajax pageMethods to call the server side method which actually check the user id availability. Since we use master page in that page so add the ScriptManager tag in master page form section and set its EnablePageMethods property true to call the server side method.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods ="true"  > </asp:ScriptManager>

Step3: Now add the following code in code behind page i.e, .cs file.
public static List<string> UserList = new List<string>()
        {
            "shimul","zakir","zafor","sohel","sumon"
        };
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        [System.Web.Services.WebMethod]
        public static string IsUserAvailable(string username)
        {
            string userAvailability = string.Empty;
            bool userExists = false;
           
            string tempOid = string.Empty;

            //Check the username in user list
            foreach (var item in UserList)
            {
                if (item.Equals(username))
                {
                    userExists = true;
                }
            }
            if (!userExists)
                userAvailability += "0";
            else
            {
               
               
                //hold suggested user id
                List<string> LstUserOID = new List<string>();
                System.Random random = new Random();
                while (LstUserOID.Count < 4)
                {
                    tempOid = string.Empty;
                  
                    //create temporary oid
                    tempOid += username + random.Next(0, 100);
                    // test is the id exists in login table

                    if (!UserList.Contains(tempOid))
                    {
                        //if not exists then put it in the list
                        LstUserOID.Add(tempOid);
                    }
                }
                foreach (var item in LstUserOID)
                {
                    userAvailability += item + "|";
                }
            }
            return userAvailability;

        }
In my method i actually use a list that is initialize with some name. I use it so that i test my code as it is working or not. And in IsUserAvailable method i test supplied user id to the list. If the list contains the usert id then it generate some id for suggestion and make string with that id which then send to the javascript function. And finally we show the id in radio button.

Step5: When i run my page I see and supply a user id and check it. I get the following screen shot.




I think that will help you little bit. If any further clarification or any suggestion please write me in a mail.

Shimul Mahmud
azkhairuzzaman@gmail.com