Tuesday, August 21, 2012

How to get the value of Textbox, CheckBoxlist, RadioButtonList, ListBox, DropDownList in javascript

In this Article you will learn how to get the values or text of textbox,CheckBoxlist,RadioButtonList,ListBox,dropdownlist in javascript.

Introduction

This Article explains you how to Raise Client Click Events for Server Controls
usage:
1.Attribute 'OnClientClick':-The OnClientClick property is used to sets a client side script or Method to be run when the Button control is clicked.
eg:OnClientClick ="return javascriptMethod()"
2.getElementById():-It is used to get the Elements in a form.This method takes an argument to access elements with a unique id attribute.
eg:document.getElementById ("textbox1");
3)getElementsByTagName():-This method takes in as argument the name of a tag element and returns an array of all matching tags elements found in the document.
eg:document.getElementsByTagName("Label");
How to get the value of textbox in javascript ?
in .aspx source code
<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">
    function getTxt()
    {
     var txt=document.getElementById("TextBox1");
     alert(txt.value);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server" Height="16px" Style="z-index: 100; left: 176px;position: absolute; top: 32px" Width="96px"></asp:TextBox>
  <asp:Button ID="Button1" runat="server" Font-Bold="True" Style="z-index:101;left:184px;position:absolute; top:64px" Text="Click" Width="56px"
 OnClientClick ="return  getTxt()"/>
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="0.8em" Style="z-index: 103;left: 96px; position: absolute; top: 32px" Text="User Name:"></asp:Label>
    </div>
    </form>
</body>
</html>
 Image of textbox

 How to get the text of CheckBoxList in Javascript?

<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function chkboxMeth()
    {
      var chkbox = document.getElementById("CheckBoxList1");
      var inputArr = chkbox.getElementsByTagName('input');
      var labelArr = chkbox.getElementsByTagName('label');
      var sum="";
     for (var i=0; i
     {
      if (inputArr[i].checked == true)
{
sum = sum + labelArr[i].innerText;
}
    }
alert(sum);
return false;
  }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" BackColor="#00CC99" Font-Bold="True" ForeColor="#FF0066">
            <asp:ListItem Value="1">Apple</asp:ListItem>
            <asp:ListItem Value="2">Banana</asp:ListItem>
            <asp:ListItem Value="3">Grapes</asp:ListItem>
        </asp:CheckBoxList>
        <asp:Button ID="Button1" runat="server" Style="position: absolute; z-index: 102; left: 400px; top: 48px;" Text="Click" OnClientClick =" return chkboxMeth()" BackColor="#CCCC66" Font-Bold="True" Width="64px"/>
    </div>
    </form>
</body>
</html>
 
Image of CheckBoxlist

How to get the value or text of radioButtonList in javascript?

<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">            
  function GetRadioButtonSelectedValue()
  {
      var radio = document.getElementById('radiobuttonlist1');
      var inputArr = radio.getElementsByTagName('input');
      var labelArr = radio.getElementsByTagName('label');
     for (var i=0; i
     {
        if (inputArr[i].checked )
         {
          alert("Selected Value:"+inputArr[i].value+" 
Selected Text :"+labelArr[i].innerText);
          inputArr[i].checked =false  
         }
     }

  } 
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
    <asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" ForeColor="Blue" BackColor="#E0E0E0" Font-Bold="True" Font-Names="Verdana" Font-Size="Small">
          <asp:ListItem Text="ASP.NET" Value="1" ></asp:ListItem>
          <asp:ListItem Text="SilverLight" Value="2"></asp:ListItem>
          <asp:ListItem Text="C#.NET" Value="3"></asp:ListItem>
   </asp:RadioButtonList>

   <asp:Button ID="Button1" runat="server" Style="position: static;" Text="Select"
     OnClientClick =" return GetRadioButtonSelectedValue(); " />
</div>
    </form>
</body>
</html>
Image of RadioButton List
How to get the selected value or text  of dropdown in javascript?
 <head runat="server">
    <title>Untitled Page</title>
     <script type ="text/javascript">
      function ddlmeth()
      {
var ddl=document.getElementById("DropDownList1");
     alert("Selected Value: "+ddl.value +"  "+"Selected Text: "+ddl[ddl.selectedIndex].innerText);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:Button ID="Button1" runat="server" Style="position: absolute; z-index: 103; left: 200px; top: 120px;" Text="click" OnClientClick ="return ddlmeth()" ForeColor="#FF0066" Width="72px"  />
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" Style="z-index: 102;
            left: 208px; position: absolute; top: 8px">
            <asp:ListItem Value="1">ASP.NET</asp:ListItem>
            <asp:ListItem Value="2">VB.NET</asp:ListItem>
            <asp:ListItem Value="3">C#.NET</asp:ListItem>
        </asp:DropDownList>
   
    </div>
    </form>
</body> 

Image of dropdownlist

How to get the text or value of ListBox in JavaScript?
<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">
    function getListBox()
    {
     var listbox=document.getElementById("ListBox1");
 
     alert("Selected Value:"+listbox.value+"  
            Selected Text:"+listbox[listbox.selectedIndex].innerText);
    }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" BackColor="#FFFFFF" Font-Bold="True" Font-Names="Verdana"ForeColor="#660066" Height="80px" Style="z-index: 100; left: 240px; position: absolute; top: 48px" Width="80px">
            <asp:ListItem Value="1">SilverLight</asp:ListItem>
            <asp:ListItem Value="2">Ajax</asp:ListItem>
            <asp:ListItem Value="3">JQuery</asp:ListItem>
        </asp:ListBox>
 
        <asp:Button ID="Button1" runat="server" Font-Bold="True" Style="z-index: 102; left: 336px; position: absolute; top: 72px" Text="Click" Width="56px"  
   OnClientClick ="return getListBox();"/>
    
    </div>
    </form>
</body>
</html>
Image of ListBox

Display Popup message before session expiry time and Extend Session if they want to extend in asp.net C#

Write below java script function in .aspx page if u are not using master page..other wise write this function Master page .aspx page

<script language=JavaScript>


    var secondsPassed = 0;
    var minutesBeforeLoggedOut = 0;
    var minutesToWarning = 0;

    function ShowTimePassed() {

        minutesBeforeLoggedOut = parseInt(minutesBeforeLoggedOut);
        secondsPassed += 1;

        if (minutesBeforeLoggedOut == -1) {
            if (secondsPassed == 30) {
                var img = new Image(1, 1);
                img.src = 'KeepAlive.aspx?date=' + escape(new Date());
                secondsPassed = 0;
            }
        }
        else {
            if (secondsPassed == minutesToWarning * 60) {
                var answer;

                var currentTime = new Date();
                var expiredTime = new Date();
                var minutes = expiredTime.getMinutes();
                minutes += minutesBeforeLoggedOut;
                expiredTime.setMinutes(minutes);

                if (minutesBeforeLoggedOut == 1) {

                    answer = confirm("It is now " + currentTime.toLocaleTimeString() + " You have " + minutesBeforeLoggedOut + " minute left before getting logged out. Do you want to extend the session?");

                }
                else {

                    answer = confirm("It is now " + currentTime.toLocaleTimeString() + " You have " + minutesBeforeLoggedOut + " minutes left before getting logged out. Do you want to extend the session?");


                } if (answer) {
                    var img = new Image(1, 1);
                    img.src = 'KeepAlive.aspx?date=' + escape(new Date());
                    secondsPassed = 0;
                    currentTime = new Date();
                    if (currentTime > expiredTime) {
                        alert("You've exceeded the time needed to extend the session. You will be logged out now");
                        window.location = loginUrl;
                    }
                }
            }
        }
    }

    window.setInterval('ShowTimePassed()', 1000);
 

</script>


write below two function is .aspx.cs file


  private void keepAlive()
    {

        //figure out the full url of the logout page configured in web.config + the return url which is the current page

        String logoutUrl = FormsAuthentication.LoginUrl + "?ReturnUrl=" + Request.Url;

         String minutesToWarning = "";
        //figure out how many minutes before time out the user wants to get warned.

        String minutesBeforeLoggedOut = "1";
        if (minutesBeforeLoggedOut == null || minutesBeforeLoggedOut == "")
        {
            minutesBeforeLoggedOut = "1";
        }

        //if the user selected "-1", then it never gets timedout. If not, figure out, how many minutes after the page loaded, give the user the warning
        if (!minutesBeforeLoggedOut.Equals("-1"))
        {
            int formsTimeout = GetFormsTimeout();
         //   int formsTimeout = Session.Timeout;
            minutesToWarning = Convert.ToString(formsTimeout - Convert.ToInt32(minutesBeforeLoggedOut));
        }

       String script = @"
                  

<script language=JavaScript>
                        var minutesToWarning = " + minutesToWarning + @";
                        var minutesBeforeLoggedOut = " + minutesBeforeLoggedOut + @";
                        var loginUrl  = '" + logoutUrl + @"';
                   

</script>
                    ";

        if (!Page.ClientScript.IsClientScriptBlockRegistered("WarnTimeOut"))
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "WarnTimeOut", script);

    }


    private int GetFormsTimeout()
    {
        System.Xml.XmlDocument x = new System.Xml.XmlDocument();
        x.Load(Request.PhysicalApplicationPath + "/web.config");
        System.Xml.XmlNode node = x.SelectSingleNode("/configuration/system.web/authentication/forms");
        int Timeout = int.Parse(node.Attributes["timeout"].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
        return Timeout;
    }

and call  keepAlive(); function in Page_Load

 protected void Page_Load(object sender, EventArgs e)
    {
             keepAlive();
    }

and in web.config dont forget to add these lines of code

< authentication mode="Forms">
            <forms timeout="20"/>
        </authentication>


           
       

If your project contains more than one folder and more than one master page..do the same procedure for every master page in every folder in your project

Thanks & Regards

Sathish Sirikonda

Disable Right Click Button on aspx page

Disable Right Click Button on aspx page

If u want to restrict any user  not to copy ur website content so you use this script in tag 

<script language=JavaScript>
var message = "Right Click not allowed!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")
</script>