Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

April 14, 2021

Download Excel File using AJAX in jQuery

The Excel file can be downloaded as BLOB using jQuery AJAX and XmlHttpRequest (XHR) request. Once the file is successfully sent by the server, it could be downloaded using the Response object inside the Success event handler of jQuery AJAX function.

In this post I will explain the sample code to download the Excel file using AJAX in jQuery.

Lets say the following javascript function DownloadFile is called when user clicked the Download button on the web page. It accepts an arbitrary parameter fileId, you can use any other parameter like filename etc.

Inside the DownloadFile function, you can pass the url(or an accessible file path on server) in the URL parameter of the jQuery AJAX call.

Inside the success callback of AJAX function, we can read and download the target file as byte array from the xhr object. We read the response object as Blob.

function DownloadFile(fileId) {
        $.ajax({
            type: "POST",
            url: "MyController/MyAction",
            data: JSON.stringify({ fileId: fileId }),
            contentType: "application/json; charset=utf-8",
            xhrFields: {
                responseType: 'blob'
            },
            success: function (response, status, xhr) {

                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');

                if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }
                var linkelem = document.createElement('a');
                try {
                    var blob = new Blob([response], { type: 'application/octet-stream' });

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        //   IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            // use HTML5 a[download] attribute to specify filename
                            var a = document.createElement("a");

                            // safari doesn't support this yet
                            if (typeof a.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }

                } catch (ex) {
                    console.log(ex);
                }
            },
            failure: function (response) {
                console.log(response.d);
            },
            error: function (response) {
                console.log(response.d);
            }
        });         
    }

You can use the same code to download any binary file, like PDF etc.

Since we are creating html anchor element and simulate click to download file at client. Its good idea to also remove the link once you finished working.

In the following jquery code snippet we are creating anchor element, appending to the body tag and at the end we also removed it.

var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a); 

April 18, 2019

How to use jQuery with Angular 7

In this post I will explain how to setup jQuery with Angular.

Step # 1 - Install jQuery using npm

Go to the root of the Angular project where angular.json file is placed, and run the following command to install jQuery dependency.

 npm install --save jquery

Step # 2 - Add jQuery script reference in scripts array

You can now directly add jQuery script reference in index.html file, but a better approach would be to add the relative path in the scripts array in angular.json file.

 "scripts": [
  "node_modules/jquery/dist/jquery.min.js"
  ]

Step # 3 - Use jQuery in component

We need to declare the variable($) for jQuery as following.

 declare var $: any;

Here we have defined $ variable with data type any to satisfy TypeScript compiler.

We have setup jQuery. Now we can write the jQuery code inside ngOnInit event of the component.

Here is sample code for AppComponent with jQuery variavble($) declarartion and its use in ngOnInit function.

 import { Component, OnInit  } from '@angular/core';
 
 declare var $: any;
 
 @Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
 })
 export class AppComponent implements OnInit {
   title = 'jQuery with Angular';

   public ngOnInit()
   {
   $(document).ready(() => {
    $('#myDiv').html('Hello world from jQuery');
   });
   }
 }

Where myDiv is the id of any empty div placed inside app.component.html template.

That's all set. Now when you run the component you should be able to see the jQuery message inside the target div.

I hope this helps some of you who may be looking to setup jQuery in Angular component.

March 11, 2019

jQuery - Find elements with multiple attribute values.

In this post we will see how to write selector string with multiple attribute values. For example, I have <ul> element with a number of child <li> elements, have placed this <ul> element inside <div> with id='#divItems'. An example layout may be like this:

 <div id="divItems">
  <ul>
   <li id="1" data-accountid="1" data-branch="1"<Item1>/li>
   <li id="2" data-accountid="1" data-branch="1"<Item1>/li>
   <li id="3" data-accountid="1" data-branch="3"<Item1>/li>
   <li id="4" data-accountid="2" data-branch="1"<Item1>/li>
   <li id="5" data-accountid="2" data-branch="2"<Item1>/li>
   <li id="6" data-accountid="3" data-branch="1"<Item1>/li>
   <li id="7" data-accountid="3" data-branch="2"<Item1>/li>
   <li id="8" data-accountid="3" data-branch="3"<Item1>/li>
   <li id="9" data-accountid="4" data-branch="1"<Item1>/li>
   <li id="10" data-accountid="4" data-branch="2"<Item1>/li>
   
  </ul>
 </div>

In jQuery you can select desired element for single attribute value (say id), like this:

 var liObject = $("#divItems ul li[id='2']);

You can also find by your own custom data attribute if it is being specified with the element, lets say each li element has attribute data-accountid. Syntax will be same.

 var liObject = $("#divItems ul li[data-accountid='3']);

Take another step, you can specify multiple attributes in selector string. Lets say you can have multiple li elements with data-accountid='3', but you also want to narrow down your filter criteria by further looking for another attribute data-branchid. Here is how you can specify multiple attributes.

 var liObject = $("#divItems ul li[data-accountid='3'][data-branchid='1']);

Similarly you can add any number of attribute filters in selector string.

I hope this helps some of you who get stuck with a similar problem.

September 17, 2018

jQuery AJAX failed calling ASP.NET WebMethods

Recently I migrated all code files from ASP.NET Web Application to ASP.NET WebSite (with Framework 4.5.2), because of some requirements we need to move towards website template. At the time I faced this issue, all the ajax calls stopped working. When I placed breakpoint on WebMethod, It was not getting fired.

Here is the WebMethod code:


[WebMethod(EnableSession = true)]
public static string GetPageSummary(string pageid)
{
 string html = "";

 if (!string.IsNullOrEmpty(pageid))
 {
  html = PageHelper.GetPageSummaryHtml(pageid);
 }

 return html;
}

And here is the jquery Ajax call for that method:

$.ajax({

  type: "POST",
  url: "MyPage.aspx/GetPageSummary",
  data: "{ 'pageid':'" + id + "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
   showModelPopupForSummary(response.d)
  },
  error: function (response) {   
   //error-handling code...
  }
 });

It all looks fine and working in previous project, but not with new WebSite project.

After spending way too much time on this, I found out the solution for this.

You have to change enum value for AutoRedirectMode. Go to App_Code/RouteConfig.cs, inside RegisterRoutes() method, you will see this line:

 settings.AutoRedirectMode = RedirectMode.Permanent;

Change the enum value to RedirectMode.Off, final statement would be:

 settings.AutoRedirectMode = RedirectMode.Off;

After changing this all my ajax calls started working successfully.

August 13, 2017

HTML5 - Display Arrows for Array Items on Canvas

I received this question from one of my followers, How to Display Data on Canvas. I found this interesting and dedicated some time to work on this requirement. In this post I will explain how did I achieve drawing arrows among array items' positions before and after sorting. Lets start with the same example as posted in this question.

We have the following array along-with a sorting function:

 var selectionSort = function(arr) {
  var j,i;
  var smallest;
  for(j = 0; j < arr.length ; j++)
  {
   smallest = j;
   for(i = j + 1; i < arr.length ; i++)
   {
    if(arr[i] < arr[smallest])
   {
    smallest = i;
   }
   }
  var temp;
  arr[temp] = arr[smallest];
  arr[smallest] = arr[j];
  arr[j] = arr[temp];
 }
 return arr;
 };

 var array = [6,5,4,3,2,1];
 
 array2 = selectionSort(array.slice()).slice();

At this point, we have two arrays, array is the original unsorted array and array2 is the final sorted one. And we want to display both arrays on screen with drawing arrows to show the possible movement of items in positions inside the array.

Let first setup our UI to have canvas containers where we want to display array, here is the HTML I used for this example:

 <body>

  <div id="myocontainer" style="width:70%;margin-left:100px;">
   <div style="width:300px;float: left;">
    <h2>Origianl Array</h2>
    <hr/>
    <h4 style="float:left; margin-left:50px;margin-top:5px;"><u>Index</u></h4>
    <h4 style="float:left; margin-left:40px;margin-top:5px;"><u>Value</u></h4>
    <canvas id="cnvTable1" width="100%" height="100%"></canvas>
   </div>
   <div style="width:300px;float:left; margin-left:300px;">
    <h2>Sorted Array</h2>
    <hr/>
    <h4 style="float:left; margin-left:50px;margin-top:5px;"><u>Index</u></h4>
    <h4 style="float:left; margin-left:40px;margin-top:5px;"><u>Value</u></h4>
    <canvas id="cnvTable2"></canvas>
   </div>
  </div>
  
 </body>

To make things simpler I created a class ArrayItem to represent array items by maintaining their index, value and with two helper functions getPosX, getPosY. getPosX, getPosY respectively describes the position of items being drawn on canvas for that particular item. Here is the code for this class:

 function ArrayItem(indx, val) {
   this.index = indx;
   this.value = val;
   
   this.getPosX = function() {
  return 50;
   };
   
   this.getPosY = function() {
  return this.index * 50;
   };
 }

Since we are drawing objects on screen, in order to have better display on screen I have hard-coded values for positionX and relative value for positionY.

Next part is to create temp array of ArrayItem objects for both array and array2.

 var array1Items = [];
 $.each(array, function( index, value ) {
  array1Items.push(new ArrayItem(index, value));
 });
 
 var array2Items = [];
 $.each(array2, function( index, value ) {
  array2Items.push(new ArrayItem(index, value));
 });

Now comes the tricky part how to display array items on canvas. I write this printArray() function to display items on canvas.

 function printArray(arr1, canvasID, offsetX, offsetY)
 {
  var c = document.getElementById(canvasID);
  var ctx = c.getContext("2d");
  c.width  = 800;
  c.height = 1000;

  ctx.font="30px Georgia";
  var tempX = 50;
  var tempY = 50;
  
  $.each(arr1, function( index, value ) {
   tempX = value.getPosX() + offsetX;
   tempY = value.getPosY() + offsetY;
   
   ctx.fillText(index, tempX, tempY);
   ctx.fillText(value.value, tempX + 70, tempY);
  });
 }

It takes following parameters:

  • arr1: the array we need to print
  • canvasID: container, where we have to print array items
  • offsetX: offset of X position, or left margin from the container.
  • offsetY: offset of Y position, or top margin from the container.

Using this function we can print our arrays:

 printArray(array1Items, "cnvTable1", 10, 50);
 printArray(array2Items, "cnvTable2", 10, 50);

Now comes the final part how to draw arrows showing possible movement among array items before and after sorting process. I have used this jQuery plugin Curved Arrow to draw arrows, you can download this js file and add reference to this along-with jQuery.

 $.each(array1Items, function( index, value ) {
  offsetX = 140;
  offsetY = 170;
  
  var newArrayItem = getArrayItemAfterSort(value.value);
  if(newArrayItem != undefined)
  {
   console.log(index  + " - " + value.value + " - " + newArrayItem.index);
   
   $("#myocontainer").curvedArrow({
    p0x: value.getPosX() + offsetX,
    p0y: value.getPosY() + offsetY,
    p1x: value.getPosX() + offsetX,
    p1y: value.getPosY() + offsetY,
    p2x: newArrayItem.getPosX() + 570 + offsetX,
    p2y: newArrayItem.getPosY() + offsetY,
    lineWidth: 3,
    size:10
   });
   
  }
 }); 
 
 function getArrayItemAfterSort(valueToFind)
 {
  var arrayItem = undefined;
  
  for (i = 0; i < array2Items.length; i++) {
   if(array2Items[i].value == valueToFind)
   {
    arrayItem = array2Items[i];
    break;
   }
  }
  
  return arrayItem;
 }

We are done with drawing arrows for array items. Lets try running this code and with the array items used in this example, you will see output similar to this:

array items

Slightly changing the sequence of array items, i.e. var array = [6,4,1,5,2,3]; , you will see output like this:

array items

April 14, 2012

jQuery with ASP.NET III - Animations

Since jQuery has emerged, interactive and more responsive web applications become easier to develop in today's world. It provides many powerful features that you could get use very efficiently with less coding, which otherwise requires more development efforts and lines of code to accomplish a single effect. In this article we will focus on animation features provided by jQuery and use animation effect in our ASP.Net website.

Background

In last post jQuery in ASP.Net II - GridView, we explored some responsive behavior with GridView control and validate our multi-line textbox to specified limit of characters. Here we set our focus on different animation methods provided:
  • Enlarging text on mousehover
  • Creating fade effect on mousehover
  • Sliding elements
  • Animating the panel
  • Hide and Display panels
  • Chain of animations
Note that we only discuss code segments here for jQuery, with assumptions that corresponding ASP.Net controls are already placed on the webpage. You will get cleared while we proceed further. We will only discuss the code placed inside the script segment required for jQuery, like:
<script type="text/javascript">
     $(document).ready(function () {
         
         // our jQuery code will goes here...

     });
    </script>

Enlarging text on mousehover

We place a label with some text displayed in it, and on mousehover we will enalrged the text inside the label by changing its font size.
var origFontSize = parseFloat($(".enlarge").css('font-size'));
    $("#content").hover(
        function () {
            $(".enlarge").css("cursor", "pointer");
            var newFontSize = origFontSize * 3;
            $(".enlarge").animate({ fontSize: newFontSize }, 300);
        },
        function () {
            $(".enlarge").animate({ fontSize: origFontSize }, 300);                    
        }
    );
Assumption : You have placed a fieldset with ID = content and dropped a Label with CssClass = enlarge, and put come text content int it. We have defined the enlarge class as :
.enlarge
    {
        font-size: 12px;
        font-family: Arial,sans-serif;
    }
  • parseFloat($(".enlarge").css('font-size')) selects our label which
    has css class enlarge, and retrieve its font-size property, parseFloat to our variable origFontSize.
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our label control to pointer
  • newFontSize set our font size variable with new size, by multiplying original font size with our multiplier scale, 3 in this case.
  • $(".enlarge").animate({ fontSize: newFontSize }, 300); here the actual method comes which do the animation on our label control. animate method takes the animation object with properties required to animate. In our case we only passed the property fontSize with our new size value newFontSize. This directs the animate method to change the properties passed as parameters with new values. And the second parameter for animate method, we passed the time span value in milliseconds. In our case it takes 300 milliseconds to changes its font-size with new value.
  • $(".enlarge").animate({ fontSize: origFontSize }, 300); Inside the
    mouseout function, we reset our fontSize with original value contained in the variable origFontSize

Creating fade effect on mousehover

Place a fieldset with id = content and put an image control inside fieldset container.
$("#content").hover(
            function () {
                $("#<%=Image1.ClientID%>").css("cursor", "pointer");
                $("#<%=Image1.ClientID%>").fadeOut(1000);
            },
            function () {
                $("#<%=Image1.ClientID%>").fadeIn(1000);
            }
        );
Assumption : You have placed a fieldset with id = content, and have an image control inside the fieldset container with ID = Image1. Set its src property to an image's path, here we create an images folder at the website's root and put our image.jpg in this folder. Also set CssClass for our image control to imagecontent, which we defined as :
.imagecontent
        {
            width: 350px;
            height: 250px;
        }
  • $("#content").hover set the hover event for our fieldset with id=content
  • Within the hover event, inside the mouseover function we set the cursor for our image control to pointer
  • fadeOut is the actual method with creates the animation effect of fadeout. It takes the parameter to set the time span consumed to create the desired effect.
  • fadeIn Inside the mouseout function, we reset our image control with fadeIn with the required time span parameter.

Sliding elements

Drop a button control to provide the user a way to click and get slide the elements. Place a div with our any html content.
$("#<%= btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();
            if ($(".slide").is(":hidden")) {
                $(".slide").slideDown("slow");
            }
            else {
                $(".slide").slideUp("slow");
            }
        });
Assumption : You have placed a Button control on the form with ID = btnSubmit. And have a div with css class code>slide, we defined as :
.slide
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            display: none;
            height: 100px;
            background-color: #148A21;
            color:#000000;
        }
  • Attach click event for button btnSubmit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $(".slide").is(":hidden") first check, if our element with css class slide is already hidden, if so, then slideDown("slow") our element. We have passed the constant timespan slow defined with jQuery, you could also change to any desired timespan value.
  • if our element is not already hidden, then we will slideUp our element with the constant timespane value slow.

Animating the panel

Drop a button control to let the user do animate the panel accordingly. Place a panel with our html content.
var regular = true;
        $("#<%=btnSubmit.ClientID%>").click(function (e) {
            e.preventDefault();

            if (regular == true) {
                $(".contentArea").animate({
                    opacity: 0.5,
                    width: "500px",
                    height: "280px",
                    fontSize: "36px",
                    borderWidth: "15px"
                }, "slow");
            }
            else {
                $(".contentArea").animate({
                    opacity: 1.0,
                    width: "300px",
                    height: "100px",
                    fontSize: "12px",
                    borderWidth: "5px"
                }, "slow");
            }

            regular = !regular;
        });
Assumption : You have dropped a button control on the form with ID = btnSubmit. Placed a panel with CssClass = contentArea, we have defined as :
.contentArea
        {
            font-size: 12px;
            font-family: Arial,sans-serif;
            width: 300px;
            height: 100px;
            background-color: #9999FF;
            border: solid;
        }
  • var regular = true define our variable to maintain the status for our panel animation.
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • regular == true first check, if we have not already applied our animation on the panel. then (".contentArea").animate() method is called with different values for different css properties we have to change or applied on our panel content, and second paramter (slow)for animate method is the timespan to consumed in the animation effect.
  • else if have already applied the animation effects, now we are reverting back to
    our original css properties for the panel. We have set our orinial values for different css properties to be set for the targeted panel.

Hide and Display panels

Lets hide and display different panels, a menu like panel headers displayed on the
web page and we explore the corresponding content panels when we clicked on any
header panel.
$(".content_head").click(function () {
            $(".content_body").hide(100);
            $(this).next(".content_body").slideToggle("slow");
        });
Assumption : You have placed a series of pairs of panels. Set CssClass = content_head for first panel, which act as menu header, and set CssClass = content_body for second panel which displays the content for that menu item. We defined these css classes as :
.content_head
    {
        width: 150px;
        height: 30px;
        background-color: #CCCCCC;
        cursor: pointer;
    }
    .content_body
    {
        display: none;
        width: 150px;
        height: 50px;
        background-color: #9999FF;
    }
  • Attach the click event for the panels with css class content_head.
  • $(".content_body").hide(100) first hide all the content elements, if already explored some other menu item and showing the content, we first hide that contents.
  • $(this).next(".content_body").slideToggle("slow") now grab the current clicked element by this and find the next content item attached for this menu item by next(".content_body"). Here we reached the content panel attached to the click menu item. Now we toggle the slide status by calling slideToggle() with constant timepspan slow.

Chain of animations

Now we place a panel box on the web page and animate it. We are not restricted to
animate our elements only once but jQuery provides the the power to chain your animation effects for any elements you want.
$("#<%=btnSubmit.ClientID%>").click(function (e) {
        e.preventDefault();
        $('.contentArea').animate({ left: "+=200"}, 2000)
                .animate({ top: "+=100"}, 700)
                .animate({ left: "-=400"}, 1200)
                .animate({ top: "-=100"}, 700)
                .animate({ left: "+=200"}, 2000);
        });
Assumption : You have dropped a button control with ID = btnSubmit
and let the user to control the animation effect by this button. Place a panel with
CssClass = contentArea, we have defined the css class as :
.contentArea
    {
        width: 50px;
        height: 50px;
        background-color: #71B3A2;
        border: solid;
        position: relative;
    }
    
  • Attach the click event for button btnSumbit.
  • e.preventDefault() stops the page from being postback, by preventing the default behavior.
  • $('.contentArea') select our panel and call animate()
    methods repetitively in a chain model. Keep min minde that the animate() methods returns object element to which it is already called, so by repetitively calling this method with continous . notation we actually calling this method for the same object in reptition pattern, because the method returns the same object to which it is called with updated object status.
  • animate({ left: "+=200"}, 2000)animates the panel by changing its position on the webpage, set its css left property to some new value, and provide the timespan 200 in milliseconds to complete the animation in this span.
  • animate({ top: "+=100"}, 700) changes the top position of the panel
    by adding some new value to its css property top.
  • animate({ left: "-=400"}, 1200) again change the left
    css property, but this time passes a negative value, so this value is now subtracted
    form the current left position of the panel on the webpage.
  • animate({ top: "-=100"}, 700) change the top css property, but this time passes a negative value, so this value is now subtracted form the current top position of the panel.
  • .animate({ left: "+=200"}, 2000); again change the left css property, and add change the left position of the panel.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

We have explored some jQuery functions for achieving animation effects. jQuery offers many useful utilities to design animation, thus empowering developers to build rich animated pages for a better interactive experience for the web users. You must explore those methods and you will find that its now become very easy to develop interactive web pages with jQuery by spending very little effort.

You could download the working copy for these code samples from my CodeProject post
jQuery with ASP.NET III - Animations

March 30, 2012

jQuery in ASP.Net II - GridView

jQuery now become the major part of web development in current environment. In my
last post Getting started with jQuery in ASP.Net, we have started to explore jQuery methods with ASP.Net common controls. Now we are going one step further in jQuery use for our ASP.Net website.
We have already explored some most common tasks we encounter with asp.net controls in jQuery. Now we will discuss :
  • Creating "Back to Top" link
  • Highlight GridView's row or cell on mouseover
  • Remove GridView's row on mouseclick
  • Remove GridView's column on mouseclick
  • Character limit validation in Multiline Textbox
Note that we are only discuss code segments here for jQuery, with assumptions that corresponding asp.net controls are already placed on the webpage. You will get cleared while we proceed further. The code segments we discussed would be placed inside the script segment required for jQuery(now it seems to become a convention for most of the developers), like:
<script type="text/javascript">
     $(document).ready(function () {
         
         // our jQuery code will goes here...

     });
    </script>

Creating "Back to Top" link

In lots of websites, we see the hyperlink "Back to Top". Let's use it in our webpage
with the help of jQuery.
$(".backtotoplink").attr("innerHTML", "Back to Top");
$(".backtotoplink").attr("title", "Back to Top");
$(".backtotoplink").attr("href", "#Top");
Assumption : You have large blocks of html content placed on the webpage, and at the end of each block, we placed a hyperlink with css class backtotoplink, which we have defined as :
.backtotoplink
    {
        color: Blue;
        cursor: hand;
    }
  • $(".backtotoplink").attr("innerHTML", "Back to Top");
    selects our hyperlink which has css class backtotoplink, and place "Back to Top" text as its content by setting its innerHTML attribute.
  • $(".backtotoplink").attr("title", "Back to Top"); sets "Back to Top" text in title attribute.
  • $(".backtotoplink").attr("href", "#Top"); sets #Top anchor target for our hyperlink showing Back to Top text.

Highlight GridView's row or cell on mouseover

GridView is the control developers used more frequently because of its different capabilities. GridView is rendered in html as tree strcuture of table,tr,td. All we have to play with these html tags to build GridView attractive or response to mouseevents.
$("# ˸%=GridView1.ClientID% ˺ td").hover(
            function () {
                $(this).addClass("highlight");
            },
            function () {
                $(this).removeClass("highlight");
            });
Assumption : You have placed a GridView control on the form with ID = GridView1. And have a css class defined some where, we have :
.highlight
        {
            background-color: #34FF6D;
        }
  • $("#<%=GridView1.ClientID%> tr").hover() attach a mouse hover event for GridView control, note that jQuery's hover
    method contains two function arguments, for mouseover and mouseleave.
    After GridView1.ClientID we place tr to select only rows (you can replace this with td to obtain same functionality with individual cell rather than row.)
  • $(this).addClass("highlight"); in mouseover event function we add class highlight to current row (or cell if you are using td in jQuery selector).
  • $(this).removeClass("highlight");in mouseleave event function we remove class highlight from current row (or cell if you specified that).

Remove GridView's row on mouseclick

Now capture click event for the row (tr) and remove all its cells (td) and itelself.
$(("#˸%=GridView1.ClientID %˺ tr(").click(function () {
                $(this).find(("td(").each(function () {
                    $(this).remove();// remove td
                });
                $(this).remove();// remove tr
            });
Assumption : You have placed a GridView control on the form with ID = GridView1.
  • Attach click event for each row.
  • Inside the click even, loop for each cell (ts) and remove it.
  • Remove the row (tr) itself too.

Remove GridView's column on mouseclick

Now capture click event for the column (th) and remove all its cells (td) and itelself. We handle event only for th, so it only works when you click on columns headers.
$("#<%=GridView1.ClientID %> th").click(function () {
            var count = $(this).closest("th").prevAll("th").length;
            $(this).parents("#˸%=GridView1.ClientID %˺")
              .find("tr").each(function () {
                $(this).find("td:eq(" + count + ")").remove();
                $(this).find("th:eq(" + count + ")").remove();
            });
        });
Assumption : You have placed a GridView control on the form with ID = GridView1.
  • Attach the click event for column headers (th).
  • .closest() begins with the current element and searches up in DOM tree till it finds a matching element.
  • .prevAll() finds all the predecessors for the current element in DOM tree. Place all founded elements length in the variable count.
  • Loop through each row (tr) in the GridView
  • Remove the td that founded with matching count.
  • Also remove the header cell (th) that founded with matching count.

Character limit validation in Multiline Textbox

When use multiline textboxes in asp.net, sometimes we need to restrict number of characters entered. In this example we restrict our textbox to accept characters in limit of 5-100
var minCount = 5;
        var maxCount = 100;
        $("#˸%=txtComments.ClientID%˺").bind("cut copy paste", function (e) {
            e.preventDefault();
        });

        $("#˸%=txtComments.ClientID%˺").keypress(function (e) {
            var strCount = $("#˸%=txtComments.ClientID%˺").val().length;
            $("#˸%=txtNumber.ClientID%˺").val(strCount);
            if ((strCount ˸ minCount) || (strCount ˺ maxCount)) {
                $("#message").text("Please enter characters in the range 5 - 100");

                if (strCount ˺ maxCount) {
                    e.preventDefault();
                }
            }
            else {
                $("#message").text("");
            }
        });
Assumption : You have placed a comments textbox control with ID = txtComments, and another textbox with ID = txtNumber to display number of characters entered.
  • Bind the event hander for cut/copy/paste operations for textbox, and disable these operations so that we could capture keypress event in order to update the character count.
  • Set txtComments value's length in the variable strCount.
  • Set this count in txtNumber text to display.
  • Check if strCount is less than minCount or strCount is greater than maxCount, then display message for user to enter characters in correct range.
  • e.preventDefault(), Finally disable the default behaviour for keypress event, to further accept any input character.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

We did some interesting things with GridView control at runtime by capturing mouse events. Then we restrict our comments textbox to accept a predefined number of characters, and notify user to input in valid range. Definitely, we can all do these tricks with traditional javascript techniques, but you see how easier it becomes with the help of jQuery.

You could download the working copy for these code samples from my CodeProject post
jQuery in ASP.NET: Part II - GridView

March 16, 2012

Let's start JQuery with ASP.Net

JQuery is the most widely used JavaScript library in web applications today, supported by an active community of developers. It is a complex JavaScript object, could be think of as a wrapper over selected DOM elements with extended functionality. JQuery is designed to be lightweight, cross browser, and CSS3 compliant. It simplifies the way DOM elements are selected, and make your operations on that elements.

jQuery can be implemented with various web platforms such as .NET, PHP and Java.
Now having the official support of Microsoft, it is now distributed with Visual
Studio (Version 2010 onwards). The library has gained popularity with ASP.NET developers. jQuery can be very easily implemented with ASP.NET controls as well as custom user controls. It can be used to validate controls using client side scripts, incorporate cool animation effects.

jQuery Selectors allow you to select DOM elements so that you can apply functionality to them with jQuery’s functional methods, and helps to encorporate CSS very easily. Using CSS means that you use selector syntax you’re probably already familiar with from HTML styling. You can select elements by id, CSS class, attribute filters, by relationship to other element and also filter conditions that can be combined together.

JQuery could be downloaded from official JQuery website .

Start JQuery

We use local copy of JQuery in our samples. Look at the head section of aspx page
where the JQuery script is placed:
<script src="js/jquery-1.4.1.js" type="text/javascript"> </script>
      <script type="text/javascript">
        
        /* INCLUDE JQUERY MARKUP HERE */

    </script> 
First script tag points to our local copy of JQuery i.e, in js folder, inside website's root directory. Second script will be populated with our JQuery implementations or any javascript code.

Our page is now enabled for using jQuery. We can now include the required jQuery
markup in the script block as follows:
<script type="text/javascript">
$(document).ready(function() {

//any jquery code goes here...

});
</ script>
All the jQuery markup on the page should be included in the $(document).ready() function. This function is executed as soon as the DOM is loaded and before the page contents are rendered.

Disallow cut/copy/paste operations for textbox

Inside the document's ready JQuery script, place the event handler's
of textbox for cut/copy/paste operations. e.g. The following code segment disallow
these operations for our textbox txtPwd :
$('#<%=txtPwd.ClientID%>').bind('cut copy paste',

            function (e) {
                e.preventDefault();
                alert("Cut / Copy / Paste are not allowed in this field");
          
            });
Assumption : Your form contains a textbox control with ID = txtPwd

e.preventDefault() is the key method provided by the script engine,
to disable the default operations to proceed further. We first stop the event for further bubble up to any other parent controls. And put any custom logic of your interest, after that, here we are notifying the user that these operations are not allowed for this textbox.

Display selected items of Checkboxlist

Again, in the document's ready function, attach the handler for our checkboxlist's click event. Within the click event handler, we traverse through each checkbox (by checking its input[type=checkbox]) by JQuery's each() function, which actually called for every check box with in this list.
$('#<%=CheckBoxList1.ClientID%>').click(function () {
                var str = "";
                
                $('#<%=CheckBoxList1.ClientID%>input[type=checkbox]')
                   .each(function () {
                    if ($(this).is(':checked')) {
                        str = str + " - " + $(this).next().text();
                    }
                });

                $('#message').text(str);
            });
Assumption : Your form contains a CheckBoxList control with ID = CheckBoxList1

Now explore some more powerful methods provided by JQuery.
  • input[type=checkbox] filters all checkboxes within our CheckBoxList1 control.
  • $(this) segment, it represents the current item being focused on by code. i.e. this time, it behaves as checkbox individual item itself.
  • .is() method, used to find the state of current checkbox, by query its checked property.
  • .next() method, retreives the next sibling for current node/control. Sinch each checkbox is rendere with two html tags, label and input. So we are at label context, and use next() method to move our focus to input (real checkbox).
  • .text() method, retrieves the text content of the current item in focused.
  • $('#message') method, retrieves the html control with id="message".
  • .text(str) method, sets the text content (passed as parameter) for the control it is called.

Get selected text/value from DropDownList

Within the document's ready function, bind the handler for our keyup and change events of DropDownList.
$('select[id$=<%=DropDownList1.ClientID%>]').bind("keyup change", 
function () {
                var selectedItem = $(this).find(":selected");
                if (selectedItem.val() != "") {
                    var msg = "Text : " + selectedItem.text() + ' Value: ' 
                               + selectedItem.val();
                    $('#message').text(msg);
                }
                else {
                    $('#message').text("");
                }
            });
Assumption : Your form contains a DropDownList control with ID = DropDownList1
  • .find() retrieves the selected item, and we put in our variable selectedItem.
  • For root item, we put empty string in its value property. So here we check if its value it empty, then remove any message placed in message div.
  • If we have non-empty string in value property, then its a valid item selected from the list. So we can get its .text() and .val() and use it for our code.

Change focus to next control on Enter key

Bind the keydownevent handler for our textboxes.
$('input:text').bind("keydown", function (e) {
                if (e.which == 13) { //Enter key
                    //to skip default behavior of the enter key
                    e.preventDefault(); 
                    var nextIndex = $('input:text').index(this) + 1;
                    var control = $('input:text')[nextIndex];
                    if (typeof control == 'object') {
                        control.focus();
                    }
                    else {
                        // we reached at last control, 
                        // return focus to first input control.
                        $('input:text:first').focus();
                    }
                }
            });
Assumption : Your form contains a series of textboxes, and no any other control
is encountered in between the series.

  • In handler function, we check for Enter key code e.which==13, when we get Enter key then first we prevent the default behaviour of Enter, and put our logic.
  • Get the next textbox's index, first get index of current textbox, then add 1 to this index. And set next textbox control in our variable control.
  • Check if typeof control is object, means we reached the next textbox properly, so set focus to it. Otherwise set focus return to our first textbox in the series.

References

ASP.Net jQuery Cookbook by Sonal Aneel Allana

JQuery is a powerful scripting library that makes developing in JavaScript easier. It has a lot of practical benefits for JavaScript developers and can perform in a variety of situations. JQuery also provides the utility functions that implement common functions useful for writing jQuery. These functions by themselves are particularly facilitates the development with ease and great pace.

You could download the working copy for these code samples from my CodeProject post
Let's start jQuery with ASP.NET