Pages

Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, October 13, 2013

Display local date and time on the site using javascript

<div id="clock">&nbsp;</div>
<script type="text/javascript">

function init ( )
{
  timeDisplay = document.createTextNode ( "" );
  document.getElementById("clock").appendChild ( timeDisplay );
}

function updateClock ( )
{
  var currentTime = new Date ( );
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );
  var currentDay = currentTime.getDate ( );
 
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
 
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"

  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay+"  "+  month_name[currentTime.getMonth()]+" "+currentDay+","+" " +currentTime.getFullYear();
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
//  document.getElementById("clock").style.fontWeight = 'bold';
}
</script>
<script>
updateClock( );
setInterval('updateClock()', 1000 );
</script>

Friday, September 6, 2013

Show loading image for 5 secs after button click

function showLoading() {
 document.getElementById('myHiddenDiv').style.display = "";
 setTimeout('document.images["myAnimatedImage"].src="work.gif"', 500000000);  
}


<span id='myHiddenDiv' style='display: none;' align="Center">
 <img id="myAnimatedImage" src="Images/ajax-loader.gif" align="middle" alt="" />
</span>


<asp:Button ID="btnUpload" runat="server" Text="Submit" CssClass="button" OnClientClick="return showDiv();" />

Thursday, November 1, 2012

Eanble Disable control on checkbox click

<script type="text/javascript">
        function EnableControl(val) {
            var sbmt = document.getElementById("<%=btnSubmit.ClientID %>");

            if (val.checked == true) {
                sbmt.disabled = false;
            }
            else {
                sbmt.disabled = true;
            }
        }
       
       
    </script>
<div style="float: left;">
            <asp:CheckBox ID="chkAgree" runat="server" Text="I Agree" onclick="EnableControl(this)"
                Checked="false" />&nbsp;&nbsp;&nbsp;
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></div>

Show/hide control if a certain selection is made in previous drop down

<script type="text/javascript">
   
    function function1(colors) {
        var col = (colors.options[colors.selectedIndex].value);
        if (col == 0 || col == 2) {
            document.getElementById("<%=divStatus.ClientID %>").style.display = "none";
        }
        else {
            document.getElementById("<%=divStatus.ClientID %>").style.display = "block";
        }
        //alert("SelectedIndex value = " + col);
    }
</script>
<asp:DropDownList ID="ddlReport" runat="server" Width="164px" onchange="function1(this);" >
                    <asp:ListItem Text="--Select--" Selected="True" Value="0" />
                    <asp:ListItem Text="Allocation Status" Value="1" />
                    <asp:ListItem Text="Compensation Structure" Value="2" />
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfvReport" runat="server" ControlToValidate="ddlReport"
                    InitialValue="0" ErrorMessage="*"></asp:RequiredFieldValidator>
<div id="divStatus" runat="server"  style="margin-top: 7em;display:none"></div>

Monday, August 27, 2012

Create Captcha Image using javascript in ASP.net C#

Default3.aspx
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" language="javascript">       
        function show()
        {
      
                var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var string_length = 5;
                var randomstring = '';
                for (var i=0; i<string_length; i++)
                {
                    var rnum = Math.floor(Math.random() * chars.length);
                    randomstring += chars.substring(rnum,rnum+1);
                }   
                var main = document.getElementById('txt1');
                main.value = randomstring;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <input type="text" id="txt1" runat="server" style="border-style: none; border-color: inherit;
            border-width: medium; background-color: black; color: red; font-family: 'Curlz MT';
            font-size: x-large; font-weight: bold; font-variant: normal; letter-spacing: 10pt;padding-left:10px;
            width: 135px;" value="1AsD" />
        <input type="button" onclick="show()" value="Change Capcha Image" />
    </div>
    <asp:TextBox ID="txtverification" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button1" runat="server" Text="Verification" OnClick="Button1_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
    </form>
</body>
</html>
 
Default3.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
    {
        if (txtverification.Text == txt1.Value)
        {
            lblmsg.Text = "Successfull";
        }
        else
        {
            lblmsg.Text = "Failure";
        }
    }

Upload Multipal Files with javascript in ASP.net C#

UploadFilesWithJavascript.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadFilesWithJavascript.aspx.cs" Inherits="UploadFilesWithJavascript" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
     <script language="javascript" type="text/javascript">
    var counter = 0;
    var counter2 = 0;
    function AddFileUpload()
    {
         var div = document.createElement('DIV');
         div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +

                         '" type="file" />' +

                         '<input  id="Button' + counter + '" type="button" ' +

                         'value="Remove" onclick = "RemoveFileUpload(this)" />';
         document.getElementById("FileUploadContainer").appendChild(div);
         counter++;
         counter2++;
         document.getElementById("btnAdd").style.visibility = "visible";        
    }
    function RemoveFileUpload(div)
    {     
         counter2--;       
         if(counter2 == 0)
            document.getElementById("btnAdd").style.visibility = "hidden";
         document.getElementById("FileUploadContainer").removeChild(div.parentNode);
    }    
    function DeleteConfirmation()
    {
        if(confirm('Are You Sure To Delete?'))       
            return true;       
        else       
            return false;       
    }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" method = "post">
    <input id="Button1" type="button" class="inputButton" value="Add New File To Upload" onclick="AddFileUpload()" /><br />
    <div id="FileUploadContainer">
                                                                        <!--FileUpload Controls will be added here -->
                                                                    </div>
                                                                    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>
</body>
</html>


UploadFilesWithJavascript.aspx.cs

protected void btnUpload_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFile PostedFile = Request.Files[i];
            if (getFileType(PostedFile.FileName) == "Image")
            {
                if (PostedFile.ContentLength > 0)
                {
                    string FileName = System.IO.Path.GetFileName(PostedFile.FileName).ToString();
                    int size = PostedFile.ContentLength;
                    PostedFile.SaveAs(Server.MapPath("Uploads\\") + FileName);
                }
            }
        }
    }
    string getFileType(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        switch (ext.ToLower())
        {
            case ".gif":
                return "Image";
            case ".png":
                return "Image";
            case ".jpg":
                return "Image";
            case ".jpeg":
                return "Image";
            default:
                return "Not known";
        }
    }

Thursday, August 23, 2012

Code to limit the textbox characters

function limitText(objTextBox, maxCharacters)
{
    if(objTextBox.innerText.length >= maxCharacters)
    {
    if((event.keyCode >= 32 && event.keyCode <=126) || (event.keyCode >= 128 && event.keyCode <= 254))
    {
        event.returnValue = false;
    }
    }
}
<asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine" Rows="6" Columns="80" OnKeyDown="javascript:limitText(this,1024)" ></asp:TextBox>

Code to deselect all the items of the Listbox

<asp:ListBox ID="lbTopics" runat="server" Width="200px" SelectionMode="Multiple" onclick="javascript:listselection();" CssClass="normalFields"></asp:ListBox>

function listselection()
{
    var listitem=document.getElementById("<%=lbTopics.ClientID %>");
    if(listitem.options[0].selected)
    {
        listitem.selectedIndex = -1;
    }
}

Friday, July 27, 2012

Validate multiple valid emails separated by semicolon

Validate multiple valid emails separated by semicolon
There are various ways to validate them
1. Using custom validator and calling the javascript

 <asp:CustomValidator ID="custValEmail" runat="server" ClientValidationFunction="validateMultipleEmailsCommaSeparated"  ErrorMessage="Invalid email(s)"></asp:CustomValidator>

 <script language="JavaScript" type="text/javascript">

 function validateEmail(field)
 {
     var regex=/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
     var matchArray=field.match(regex);
     if(matchArray==null)
         return false;
     else
         return true;
 }

 function validateMultipleEmailsCommaSeparated(source, value)
 {
     var result = document.getElementById("<%= txtEmail.ClientID %>").value.split(';');
     for(var i = 0;i < result.length;i++)
     {
         if(!validateEmail(result[i]))
         {
             value.IsValid = false;
             return false;
         }    
     }       
     value.IsValid = true;
 }
 </script>
 
2. Directly defining the regular expression in the RegularExpressionValidator control   
   
    <asp:RegularExpressionValidator ID="s" runat="server" ControlToValidate="txtEmail" ErrorMessage="Invalid email(s)" 
ValidationExpression="(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*"></asp:RegularExpressionValidator>

Thursday, December 8, 2011

Print contents of Div using Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML;
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
           
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
           
            //Print Page
            window.print();
           
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
           
            //disable postback on print button
            return false;
        }
    </script>
    <title>Div Printing Test Application by Zeeshan Umar</title>
</head>
<body>
    <form runat="server">
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return printDiv('div_print');" />
    <div id="garbage1">I am not going to be print</div>
    <div id="div_print"><h1 style="color: Red">Only Zeeshan Umar loves Asp.Net will be printed :D</h1></div>
    <div id="garbage2">I am not going to be print</div>
    </form>
</body>

Thursday, June 9, 2011

Validating textbox using single CustomValidator Control in GridView

The below code validates all the textboxes in a Gridview using a single CustomValidator control

function isValidDate(sText) {
var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;

if(sText.length==0)
return false;
else
return reDate.test(sText);
}
function isValidDecimalValue(sValue)
{
var reDecimal = /^\d{1,12}(\.(\d{1,2}))?$/;
return reDecimal.test(sValue);
}

function validateForm(source, value)
{
var isXDDateError = false;
var isGrossError = false;
var objError = document.getElementById("<%= spnError.ClientID %>");
objError.innerHTML="";
isXDDateError=ValidateDateValue();
isGrossError=ValidateGross();

if(isXDDateError || isGrossError)//Both false
{
value.IsValid = false;
}
else
value.IsValid = true;
}

function ValidateGross()
{
var obj = document.getElementsByTagName("input");
var objError = document.getElementById("<%= spnError.ClientID %>");
var objSpan, isError = false;
for(i=0; i<obj.length; i++)
{
if(obj[i].name.indexOf("txtGross") > 0)
{
if(!isValidDecimalValue(obj[i].value))
{
isError = true;
if(obj[i].parentNode != null)
{
for(j=0; j < obj[i].parentNode.childNodes.length; j++)
{
objSpan = obj[i].parentNode.childNodes[j];
if( objSpan != null && objSpan.id != undefined)
{
if(objSpan.id.indexOf("spnGross") == 0)
{
objSpan.innerText = "*";
}
}
}
}
}
else
{
if(obj[i].parentNode != null)
{
for(j=0; j < obj[i].parentNode.childNodes.length; j++)
{
objSpan = obj[i].parentNode.childNodes[j];
if( objSpan != null && objSpan.id != undefined)
{
if(objSpan.id.indexOf("spnGross") == 0)
{
objSpan.innerText = "";
}
}
}
}
}
}
}
if(isError)
{
if(objError.innerHTML.length>0)
objError.innerHTML+="* Please enter a value for Gross.</br>"
else
objError.innerHTML="* Please enter a value for Gross.</br>"
objError.display="block";
}

return isError;
}

<span id="spnError" runat="server" style="color:Red"></span>
<asp:CustomValidator ID = "CustomValidator1" runat = "server" ClientValidationFunction = "validateForm"></asp:CustomValidator>
<asp:Button ID="btnSave" CausesValidation="true" runat="server" Visible="true" class="tdsButton" Text="Save"
align="right" OnClick="btnSave_Click" />
<asp:GridView ID="HoldingsGrid" runat="server">
<Columns>
<asp:TemplateField HeaderText="Gross" SortExpression="SortOnGross">
<ItemTemplate>
<asp:Label ID="lblGross" runat="server" Text='<%# Bind("PAYMENT_GROSS_LOCAL_CUST") %>' />
<asp:TextBox ID="txtGross" runat="server" />
<span id="spnGross" style="color:Red" ></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Validate date using Javascript dd/mm/yyyy

<html>
<head>
<title>Date Example</title>
<script type="text/javascript">
    function isValidDate(sText) {
        var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
        return reDate.test(sText);
    }
    function validate() {
        var oInput1 = document.getElementById("txt1");
        if (isValidDate(oInput1.value)) {
            alert("Valid");
        else {
            alert("Invalid!");
        }
    }
</script>
</head>
<body>
    <P>Date: <input type="text" id="txt1" /><br />
    example: 06/07/2005<br />
    <input type="button" value="Validate" onclick="validate()" /></p>
</body>
</html>

Friday, May 27, 2011

Code to upload multiple files using javascript like Gmail

Here is the code to upload multiple files using javascript
Default.aspx
<head runat="server"><title>Untitled Page</title><script language="javascript" type="text/javascript">var counter = 0;
var counter2 = 0;
function AddFileUpload()
{
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
'" type="file" />' +
'<input id="Button' + counter + '" type="button" ' +
'value="Remove" onclick = "RemoveFileUpload(this)" />';
document.getElementById("FileUploadContainer").appendChild(div);
counter++;
counter2++;
document.getElementById("btnAdd").style.visibility = "visible";
}
function RemoveFileUpload(div)
{
counter2--;
if(counter2 == 0)
document.getElementById("btnAdd").style.visibility = "hidden";
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
function DeleteConfirmation()
{
if(confirm('Are You Sure To Delete?'))
return true;
else
return false;
}
</script>head>body><form id="form1" runat="server" enctype="multipart/form-data" method="post"><input id="Button1" type="button" class="inputButton" value="Add New File To Upload"onclick="AddFileUpload()" /><br /><div id="FileUploadContainer"><!--FileUpload Controls will be added here --></div><asp:button id="btnUpload" runat="server" text="Upload" onclick="btnUpload_Click" /></form>body>
</
Default.aspx.cs
protected void btnUpload_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (getFileType(PostedFile.FileName) == "Image")
{
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName).ToString();
int size = PostedFile.ContentLength;
PostedFile.SaveAs(Server.MapPath("Uploads\\") + FileName);
}
}
}
}
string getFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".gif":
return "Image";
case ".png":
return "Image";
case ".jpg":
return "Image";
case ".jpeg":
return "Image";
default:
return "Not known";
}
}

</
<

Code to create capcha image using javascript with sound effect

Here are few things that you need to do before you run this code.
1. Create a folder "SoundFiles" at the root of the project.
2. Add reference of "Interop.SpeechLib.dll" file so that it is added in the bin folder.
3. Place the "q.wav" and "sound.png" file at the root of the project.
Here is the code to create capcha image using javascript with sound effect
Default.aspx
<head runat="server"><title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function show()
{
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

var string_length = 5;
var randomstring = '';
for (var i=0; i<string_length; i++)
{
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
var main = document.getElementById('txt1');
main.value = randomstring;
document.getElementById("Button1").click();

}
</script>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" runat="server" id="txt1"  style="border-style: none; border-color: inherit;
            border-width: medium; background-color: black; color: red; font-family: 'Curlz MT';
            font-size: x-large; font-weight: bold; font-variant: normal; letter-spacing: 10pt;padding-left:10px;
            width: 135px;"  />
        <input type="button" onclick="show()" value="Change Capcha Image" />
        <img alt="" src="sound.png" onclick="javascript:playSound();" />      
    </div>
    <asp:TextBox ID="txtverification" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button1" runat="server" Text="Verification" style="display:none" OnClick="btn1_Click" />
    <asp:Button ID="Button2" runat="server" Text="Verification" OnClick="Button2_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
    <div id="divsound" ></div>
    </form>
</body>
Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "<script language='javascript' type='text/javascript'>show();</script>";
ClientScript.RegisterStartupScript(this.GetType(), "script", script);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (txtverification.Text == txt1.Value)
{
lblmsg.Text = "Successfull";
}
else
{
lblmsg.Text = "Failure";
}
}
protected void btn1_Click(object sender, EventArgs e)
{
SpeechLib.SpFileStream spfilestream;
string WAVFileName=Convert.ToDateTime(DateTime.Now).ToString("MMddyyyymmss") + ".wav";
File.Copy(MapPath("q.wav"), MapPath("SoundFiles/" + WAVFileName), true);
string filename = MapPath("SoundFiles/" + WAVFileName);
spfilestream = new SpFileStreamClass();
spfilestream.Open(filename, SpeechStreamFileMode.SSFMCreateForWrite, false);
SpeechLib.ISpeechVoice ispvoice1 = new SpVoiceClass();
ispvoice1.AudioOutputStream = spfilestream;
ispvoice1.Speak(txt1.Value.ToString(), SpeechVoiceSpeakFlags.SVSFDefault);
ispvoice1.Rate =10000;
ispvoice1.WaitUntilDone(-1);
spfilestream.Close();
string script = "<script language='javascript' type='text/javascript'> "+
" function playSound() {"+
" document.getElementById('divsound').innerHTML=\"<embed src='SoundFiles/" + WAVFileName + "' hidden='true' autostart='true' loop='false' />\"" +
" } </script>";
ClientScript.RegisterStartupScript(this.GetType(), "script", script);
}

Thursday, January 20, 2011

Call server side function on Function key press

<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e) {
    var KeyID = (window.event) ? event.keyCode : e.keyCode; switch (KeyID) {
        case 118:
            __doPostBack('__Page', 'F7');
            break;       
        case 39:
            //__doPostBack('__Page', 'ArrowRight');
            __doPostBack('Button2', '')
            break;
        case 40:
            __doPostBack('__Page', 'ArrowDown'); break;
    }
}
</script>

<form id="form1" runat="server">
     <a id="LButton3" href="javascript:__doPostBack('Button2','')">LinkButton</a>
     <a id="A1" href="DisableBackButton.aspx">LinkButton</a>
     <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />   
</form>
Server Side Code
protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(DateTime.Now.ToString());
        Page.ClientScript.GetPostBackEventReference(this, "");
        string eventArgs = Request["__EVENTARGUMENT"]; if (!string.IsNullOrEmpty(eventArgs))
        {
            switch (eventArgs)
            {
                case "F7":
                    a("F7");
                    break; 
            }
        }
    }
public void a(string s)
    {
        Response.Write(s);
    }

Tuesday, January 4, 2011

Create Capcha using Javascript

<script language="javascript">
        function show() {
             var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var string_length = 5;
                var randomstring = '';
                for (var i=0; i<string_length; i++)
                {
                    var rnum = Math.floor(Math.random() * chars.length);
                    randomstring += chars.substring(rnum,rnum+1);
                }   
                var main = document.getElementById('txt1');
                main.value = randomstring;
        }
    </script>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" id="txt1" runat="server" style="border-style: none; border-color: inherit;
            border-width: medium; background-color: black; color: red; font-family: 'Curlz MT';
            font-size: x-large; font-weight: bold; font-variant: normal; letter-spacing: 10pt;
            width: 120px;" value="1AsD" />
        <input type="button" onclick="show()" value="Change" />
    </div>
    <asp:TextBox ID="txtverification" runat="server"></asp:TextBox>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Button1" runat="server" Text="Verification" OnClick="Button1_Click" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
    </form>
</body>
Code Behind write:
protected void Button1_Click(object sender, EventArgs e)
    {
        if (txtverification.Text == txt1.Value)
        {
            lblmsg.Text = "Successfull";
        }
        else
        {
            lblmsg.Text = "Failure";
        }
    }

Dopostback on Key Press using javascript

<script type="text/javascript">
document.onkeyup = KeyCheck;
function KeyCheck(e) {
    var KeyID = (window.event) ? event.keyCode : e.keyCode; 
//alert("KeyId="+KeyID);
switch (KeyID) {
        case 118:
            __doPostBack('__Page', 'F7');
            break;
        case 119:
            __doPostBack('__Page', 'F8');
            break;
        case 120:
            __doPostBack('__Page', 'F9');
            break;
        case 121:
            __doPostBack('__Page', 'F10');
            break;
    }
}
</script>
Code Behind write:
protected void Page_Load(object sender, EventArgs e)
    {
        Page.ClientScript.GetPostBackEventReference(this, "");
        string eventArgs = Request["__EVENTARGUMENT"]; if (!string.IsNullOrEmpty(eventArgs))
        {
            switch (eventArgs)
            {
                case "F7":
                    a("F7");
                    break;
                case "F8":
                    a("F8");
                    break;
                case "F9":
                    a("F9");
                    break;
                case "F10":
                    a("F10");
                    break;
            }
        }
    }
   public void a(string str)
    {
         Response.Write("You pressed : " + str);
    }

Wednesday, December 22, 2010

Printer friendly using Javascript

<script language="javascript" type="text/javascript">
        function PrintThisPage() {
            var sOption = "toolbar=no,location=no,directories=yes,menubar=no,";
            sOption += "scrollbars=yes,width=750,height=600,left=100,top=25";
            var sWinHTML = document.getElementById('printcontent').innerHTML;
            var winprint = window.open("", "", sOption);
            winprint.document.open();
            winprint.document.write('<html><LINK href=\'Includes/Css/style.css\' rel=Stylesheet><body>');
            winprint.document.write('<br/><a href=\'javascript:window.print();\'>Print</a>');
            winprint.document.write(sWinHTML);
            winprint.document.write('<br/><a href=\'javascript:window.print();\'>Print</a>');
            winprint.document.write('</body></html>');
            winprint.document.close();
            var oAvail = winprint.document.getElementById('divAvail')
            if (oAvail != null) {
                oAvail.style.overflow = "visible";
            }
            winprint.focus();
        }
</script>
<div id="printcontent" style="width: 100%">This content will be opened in a new window </div>
<asp:ImageButton ID="btnPrint" runat="server" ImageUrl="~/Includes/Images/printerIcon.gif"
                    AlternateText="Print" CausesValidation="false" OnClientClick="javascript:PrintThisPage();" />

Tuesday, December 7, 2010

Calling Server side function using javascript

Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.

Default.aspx
<script type='text/javascript'>
       function DisplayMessage() {
            PageMethods.Message("Amit",OnGetMessageSuccess, OnGetMessageFailure);
        }
        function OnGetMessageSuccess(result, userContext, methodName) {
            alert(result);
        }
        function OnGetMessageFailure(error, userContext, methodName) {
            alert(error.get_message());
        }

function CallMe(src, dest) {
            var ctrl = document.getElementById(src);
            // call server side method
            PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
        }
        // set the destination textbox value with the ContactName
        function CallSuccess(res, destCtrl) {
            var dest = document.getElementById(destCtrl);
            dest.value = res;
        }
        // alert message on some failure
        function CallFailed(res, destCtrl) {
            alert(res.get_message());
        }
    </script>
<body>
    <form id='form1' runat='server'>
    <asp:ScriptManager ID='ScriptManager1' runat='server'  EnablePageMethods='true' />
<div>
            <input type='submit' value='Get Message' onclick='DisplayMessage();return false;' 

/>
<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox
            ID="txtId1" runat="server"></asp:TextBox>
        <br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />

</div>
</form>
</body>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
                    }
    }
[System.Web.Services.WebMethod]
    public static string Message(string str)
    {
        return str;
    }

[System.Web.Services.WebMethod]
    public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationSettings.AppSettings["ConnectionString"];
            conn = new SqlConnection(connection);
            string sql = "Select sEmpFName from EMP_EmpPersonal where iEmployeeId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            if (contNm.Length > 0)
                return contNm;
            else
                return "No record found.";
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }