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

3 comments:

  1. AnonymousJune 24, 2012

    Thank you for adding the reference. Appreciate it.

    ReplyDelete
    Replies
    1. Thank you very much Eowen for pointing out my mistake. although it is not done deliberately, but I thought of as it does'nt matter so much. The only intention is to provide a working copy of code exmaples that i have studied to developers like me.

      Delete
  2. AnonymousJune 27, 2012

    No worries. Since you have read and practised the codes in the book, see if you can leave your feedback on Amazon (http://www.amazon.com/ASP-NET-jQuery-Cookbook-Sonal-Allana/dp/1849690464). We are pushing for an updated edition of the book and your review will certainly help us.

    Wish you all the best in your jQuery studies.

    ReplyDelete