Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Saturday, June 21, 2014

JQuery/JavaScript Tips n Tricks

1. Check Radio button list value using JQuery and display message.

function rblStatus()
{
     var rss = $('#<%=RadioButtonList.ClientID %> input[type=radio]:checked').val();
     if (rss != 'Pending' && rss != 'Updated' && rss != 'Disapproved')
     {
          msg = "Please Select Status";
          alert(msg);
          return false;
      }
      else
     {
          return true;
     }
 }

2. Jquery Code to check all checkboxes in a gridview

function SelectAllCheckboxes(chk)
{
    $('#<%=gridview.ClientID%>').find("input:checkbox").each(function ()
    {
      if (this != chk) { this.checked = chk.checked; }
    });
}

3. Show / Hide Any server control using Jquery

$("#<%=ASPControlName.ClientID%>").css("display", "none");  //Hide
$("#<%=ASPControlName.ClientID %>").css("display", "block"); //Show

4. Uncheck ASP RadioButtonList

$("table[id$=ASPControlName] input:radio:checked").removeAttr("checked")

5. Assign Value to an ASPControl

$("#<%=ddlStatus.ClientID %>").val('USERVALUE');  //USERVALUE can be any varchar value.


6. Find Gridview row count

 var gvCount = $("#<%=Gridview.ClientID %> tr").length;
  if (gvCount > 0)
 {
     alert("Count is:"+gvCount );
  }
  else
 {
     alert("No rows available");
 }

7. Print data in using client side Code using JavaScript

Step 1: Create table to be displayed under div.

     <div id="div1" runat="server" visible="false">
      <table border="1" cellpadding="1" cellspacing="1" id="PrintSlot" align="center">
        <tr>
           <td align="center" >
             <asp:Label ID="Label6" runat="server" Text="Print Me"></asp:Label>
           </td>
        </tr>
     </table>
   </div>

Step 2: JavaScript Function to print the content.

    function printData()
    {
            var divToPrint = document.getElementById("PrintSlot");  // Pass ID of table
            newWin = window.open("");
            newWin.document.write(divToPrint.outerHTML);
            newWin.print();
    }

Monday, November 25, 2013

Positioning an AutoCompleteExtender list in relation to its target control

To make the Auto Complete Extender display always below the Target textbox using JavaScript.

Step 1: Create a function in JavaScript as mentioned below

function resetPosition(object, args) {
    var tb = object._element;
    var tbposition = findPositionWithScrolling(tb);
    var xposition = tbposition[0];
    var yposition = tbposition[1] + 20; // 22 textbox height
    var ex = object._completionListElement;
    if (ex)
        $common.setLocation(ex, new Sys.UI.Point(xposition, yposition));
}
function findPositionWithScrolling(oElement) {
    if (typeof (oElement.offsetParent) != 'undefined') {
        var originalElement = oElement;
        for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
            if (oElement != originalElement && oElement != document.body && oElement != document.documentElement) {
                posX -= oElement.scrollLeft;
                posY -= oElement.scrollTop;
            }
        }
        return [posX, posY];
    } else {
        return [oElement.x, oElement.y];
    }
}

Step 2: Add the following code in the AjaxControlToolkit: AutoCompleteExtender

 OnClientShown="resetPosition" 

 
Save your code and refresh the page issue has been resolved..!!

Thursday, July 11, 2013

How to make a text box take only numeric input or any specific input as per user's requirement using JavaScript

In order to insert only numeric value from textbox this JavaScript code could be applied.
Same code can be modified to restrict the users to enter different keyboard inputs as per requirement.
This can be done by changing the ASCII value mentioned in the JavaScript file.


JAVASCRIPT CODE:

write this function under the JavaScript code.

 function isNumber(event)
   {
            var KeyBoardCode = (event.which) ? event.which : event.keyCode;
            if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57))
            {
                return false;
            }
            return true;
    }


HTML CODE:

use this code in the textbox field to perform the required operation.

onkeypress="return isNumber(event)"

One can make the text box readonly and nothing can be pasted into that by adding the following script in textbox:

onKeyPress = "javascript: return false;" onPaste = "javascript: return false;"

Sunday, April 28, 2013

Download / Upload any file and Display Message using C# in ASP.NET

* To display information using message box in ASP.NET page from server side code.

static public void DisplayAJAXMessage(Control page, string msg)
    {
            string myScript = String.Format("alert('{0}');", msg);
            ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);      
    }


e.g. : DisplayAJAXMessage(this, "Hello World");
OUTPUT: 
Fig 1: Output of DisplayAjaxMessage


* Download a file from server using link button:

protected void lnkDownloadFile_Click(object sender, EventArgs e)
    {
        try
        {
            string FileName = string.Empty;
            FileName = "demo.xls"; // Any File Name with extension
            string link = Server.MapPath("<~/Folder Name/>" + FileName); //Optional Folder Name
            FileInfo myfile = new FileInfo(link);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
            Response.AddHeader("Content-Length", myfile.Length.ToString());
            Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
            Response.TransmitFile(myfile.FullName);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            DisplayAJAXMessage(this, "File Not Found");
        }
    }


private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".xls":
                // case ".csv":
                return "application/vnd.ms-excel";
            default:
                return "application/octet-stream";
        }
    }


* Upload any file to server using C# in ASP.NET 
(Note: This example shows to upload excel file (.xls) , Just change the extension of file as per requirement to upload any type file.)

  protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (UploadFile.HasFile) //FileUpload tool from ToolBox
            {
                string Extension = Path.GetExtension(UploadFile.PostedFile.FileName);
                if (Convert.ToString(Extension).ToLower() != ".xls")
                {
                    lblError.Text = "Please select a file with extension .xls before validation";
                    return;
                }
            }
            else
            {
                lblError.Text = "Please select a file with extension .xls before validation";
                return;
            }
            string uploadFileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            int index = uploadFileName.LastIndexOf('.');
            string SheetName = uploadFileName.Substring(0, index);
            string FileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            string FilePath = Server.MapPath("~//" + FileName); //Optional FolderName
            UploadFile.SaveAs(FilePath);
         }
        catch (Exception ex)
        {
           DisplayAJAXMessage(this,"Error::"+ex);

        }
    }


Happy Coding 



View Amit Lal's profile on LinkedIn

Software Developer, Academic Writing Writer

Sunday, December 16, 2012

Add a property to gridview and enable required field validator on checkbox checked event.


Add Property to a gridview to use with Javascript.

 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      #region Add-Parameter-onJavaScript-Functions
           if (e.Row.RowType == DataControlRowType.DataRow)
          {
            CheckBox chk = new CheckBox();
            chk = e.Row.FindControl("chkIsEdit") as CheckBox;
            chk.Attributes.Add("onChange", "EnableFields(" + e.Row.RowIndex.ToString() + ")");
          }
      #endregion
    }

------------------------------------------------------
Javascript Code 
------------------------------------------------------ 

Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Saturday, June 21, 2014

JQuery/JavaScript Tips n Tricks

1. Check Radio button list value using JQuery and display message.

function rblStatus()
{
     var rss = $('#<%=RadioButtonList.ClientID %> input[type=radio]:checked').val();
     if (rss != 'Pending' && rss != 'Updated' && rss != 'Disapproved')
     {
          msg = "Please Select Status";
          alert(msg);
          return false;
      }
      else
     {
          return true;
     }
 }

2. Jquery Code to check all checkboxes in a gridview

function SelectAllCheckboxes(chk)
{
    $('#<%=gridview.ClientID%>').find("input:checkbox").each(function ()
    {
      if (this != chk) { this.checked = chk.checked; }
    });
}

3. Show / Hide Any server control using Jquery

$("#<%=ASPControlName.ClientID%>").css("display", "none");  //Hide
$("#<%=ASPControlName.ClientID %>").css("display", "block"); //Show

4. Uncheck ASP RadioButtonList

$("table[id$=ASPControlName] input:radio:checked").removeAttr("checked")

5. Assign Value to an ASPControl

$("#<%=ddlStatus.ClientID %>").val('USERVALUE');  //USERVALUE can be any varchar value.


6. Find Gridview row count

 var gvCount = $("#<%=Gridview.ClientID %> tr").length;
  if (gvCount > 0)
 {
     alert("Count is:"+gvCount );
  }
  else
 {
     alert("No rows available");
 }

7. Print data in using client side Code using JavaScript

Step 1: Create table to be displayed under div.

     <div id="div1" runat="server" visible="false">
      <table border="1" cellpadding="1" cellspacing="1" id="PrintSlot" align="center">
        <tr>
           <td align="center" >
             <asp:Label ID="Label6" runat="server" Text="Print Me"></asp:Label>
           </td>
        </tr>
     </table>
   </div>

Step 2: JavaScript Function to print the content.

    function printData()
    {
            var divToPrint = document.getElementById("PrintSlot");  // Pass ID of table
            newWin = window.open("");
            newWin.document.write(divToPrint.outerHTML);
            newWin.print();
    }

Monday, November 25, 2013

Positioning an AutoCompleteExtender list in relation to its target control

To make the Auto Complete Extender display always below the Target textbox using JavaScript.

Step 1: Create a function in JavaScript as mentioned below

function resetPosition(object, args) {
    var tb = object._element;
    var tbposition = findPositionWithScrolling(tb);
    var xposition = tbposition[0];
    var yposition = tbposition[1] + 20; // 22 textbox height
    var ex = object._completionListElement;
    if (ex)
        $common.setLocation(ex, new Sys.UI.Point(xposition, yposition));
}
function findPositionWithScrolling(oElement) {
    if (typeof (oElement.offsetParent) != 'undefined') {
        var originalElement = oElement;
        for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
            posX += oElement.offsetLeft;
            posY += oElement.offsetTop;
            if (oElement != originalElement && oElement != document.body && oElement != document.documentElement) {
                posX -= oElement.scrollLeft;
                posY -= oElement.scrollTop;
            }
        }
        return [posX, posY];
    } else {
        return [oElement.x, oElement.y];
    }
}

Step 2: Add the following code in the AjaxControlToolkit: AutoCompleteExtender

 OnClientShown="resetPosition" 

 
Save your code and refresh the page issue has been resolved..!!

Thursday, July 11, 2013

How to make a text box take only numeric input or any specific input as per user's requirement using JavaScript

In order to insert only numeric value from textbox this JavaScript code could be applied.
Same code can be modified to restrict the users to enter different keyboard inputs as per requirement.
This can be done by changing the ASCII value mentioned in the JavaScript file.


JAVASCRIPT CODE:

write this function under the JavaScript code.

 function isNumber(event)
   {
            var KeyBoardCode = (event.which) ? event.which : event.keyCode;
            if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57))
            {
                return false;
            }
            return true;
    }


HTML CODE:

use this code in the textbox field to perform the required operation.

onkeypress="return isNumber(event)"

One can make the text box readonly and nothing can be pasted into that by adding the following script in textbox:

onKeyPress = "javascript: return false;" onPaste = "javascript: return false;"

Sunday, April 28, 2013

Download / Upload any file and Display Message using C# in ASP.NET

* To display information using message box in ASP.NET page from server side code.

static public void DisplayAJAXMessage(Control page, string msg)
    {
            string myScript = String.Format("alert('{0}');", msg);
            ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);      
    }


e.g. : DisplayAJAXMessage(this, "Hello World");
OUTPUT: 
Fig 1: Output of DisplayAjaxMessage


* Download a file from server using link button:

protected void lnkDownloadFile_Click(object sender, EventArgs e)
    {
        try
        {
            string FileName = string.Empty;
            FileName = "demo.xls"; // Any File Name with extension
            string link = Server.MapPath("<~/Folder Name/>" + FileName); //Optional Folder Name
            FileInfo myfile = new FileInfo(link);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
            Response.AddHeader("Content-Length", myfile.Length.ToString());
            Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
            Response.TransmitFile(myfile.FullName);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            DisplayAJAXMessage(this, "File Not Found");
        }
    }


private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".xls":
                // case ".csv":
                return "application/vnd.ms-excel";
            default:
                return "application/octet-stream";
        }
    }


* Upload any file to server using C# in ASP.NET 
(Note: This example shows to upload excel file (.xls) , Just change the extension of file as per requirement to upload any type file.)

  protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (UploadFile.HasFile) //FileUpload tool from ToolBox
            {
                string Extension = Path.GetExtension(UploadFile.PostedFile.FileName);
                if (Convert.ToString(Extension).ToLower() != ".xls")
                {
                    lblError.Text = "Please select a file with extension .xls before validation";
                    return;
                }
            }
            else
            {
                lblError.Text = "Please select a file with extension .xls before validation";
                return;
            }
            string uploadFileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            int index = uploadFileName.LastIndexOf('.');
            string SheetName = uploadFileName.Substring(0, index);
            string FileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            string FilePath = Server.MapPath("~//" + FileName); //Optional FolderName
            UploadFile.SaveAs(FilePath);
         }
        catch (Exception ex)
        {
           DisplayAJAXMessage(this,"Error::"+ex);

        }
    }


Happy Coding 



View Amit Lal's profile on LinkedIn

Software Developer, Academic Writing Writer

Sunday, December 16, 2012

Add a property to gridview and enable required field validator on checkbox checked event.


Add Property to a gridview to use with Javascript.

 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      #region Add-Parameter-onJavaScript-Functions
           if (e.Row.RowType == DataControlRowType.DataRow)
          {
            CheckBox chk = new CheckBox();
            chk = e.Row.FindControl("chkIsEdit") as CheckBox;
            chk.Attributes.Add("onChange", "EnableFields(" + e.Row.RowIndex.ToString() + ")");
          }
      #endregion
    }

------------------------------------------------------
Javascript Code 
------------------------------------------------------