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