Home Web-development ASP.NET jQuery Cookbook

ASP.NET jQuery Cookbook

By Sonal Aneel Allana
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Working with ASP.NET Controls
About this book

jQuery is a powerful, lightweight JavaScript library that simplifies various web development tasks. With the integration of jQuery with Visual Studio 2010, it has become increasingly popular for ASP.NET developers to use jQuery's awesome power in their applications. Combining jQuery and ASP.NET creates applications that are anything but lightweight. Using this Cookbook you will become adept at using this library in your ASP.NET web applications.

This cookbook shares the most powerful, impressive, and just plain handy jQuery secrets for ASP.NET developers. From substitute server-side code to corresponding client script, it shows ASP.NET developers how to get the most from jQuery in a simple, effective, and easy manner.

The cookbook takes a pragmatic approach in applying the jQuery library to ASP.NET applications. It will help you to master the use of jQuery with ASP.NET by taking you step-by-step through hands-on, practical recipes. With its help, you can learn to manipulate various ASP.NET controls like TextBox, CheckBoxList, DropDownList, BulletedList, Hyperlink, Image, and GridView as well as custom user controls. The book teaches client validation techniques thus providing a substitute for the server-side Validation Control. It explores various graphic and animation effects that can be accomplished very easily with the library to give a better interactive experience to the end user. It explores AJAX in depth and describes the use of Firebug to view / troubleshoot the corresponding request / response dialog. You will also learn to develop rich content using client scripting.

Publication date:
April 2011
Publisher
Packt
Pages
308
ISBN
9781849690461

 

Chapter 1. Working with ASP.NET Controls

In this chapter, we will cover:

  • Creating default text for TextBoxes

  • Auto focus on the first TextBox and tab on Enter key

  • Disallowing cut/copy/paste operations on a TextBox

  • Highlighting text in a TextBox and copying to the clipboard

  • Displaying selected items of a CheckBoxList

  • Selecting/deselecting all items in CheckBoxList

  • Getting selected text and value from DropDownList

  • Appending items at runtime to DropDownList

  • Creating 'Back to Top' ASP.NET Hyperlink

  • Updating URL of ASP.NET Hyperlink at runtime

 

Introduction


jQuery is the most widely used JavaScript library in web applications today. Developed by John Resig in 2006, it is supported by an active community of developers apart from the core jQuery team. It is designed to be lightweight, cross browser, and CSS3 compliant. It simplifies the way DOM elements are selected, making it easier to navigate a page. The library has powerful Ajax capabilities, event handling, and animation effects, thus enabling rapid web application development. By allowing the creation of plugins, it enables developers to build powerful capabilities on top of the core jQuery library.

jQuery can be interfaced with numerous web platforms such as ASP, PHP, .NET, and Java. With the official support of Microsoft, it is now distributed with Visual Studio (Version 2010 onwards). Microsoft is also committed to contributing to the library and its jQuery Templates, Data Link, and Globalization plugins are now accepted as official jQuery plugins.

In this chapter, we will be specifically exploring how jQuery can be used in various ways to manipulate ASP.NET controls, the result being a better interactive experience for the web user without causing additional server-side overhead.

Downloading jQuery

jQuery is available from http://jQuery.com in different types of builds based on the requirements of the application:

  • Minified version: This version is preferred for production environments. It has a smaller file size requiring shorter time to download.

  • Packed version: This is the compressed version of jQuery. Though it has a smaller file size compared to the minified version, it requires non-trivial time to unpack when downloaded by the browser.

  • Uncompressed version: This version is preferred for development environments. It has a larger file size compared to the minified and packed versions, but is suited for debugging in the development phase.

Including jQuery library

There are two ways of including the jQuery library on the web page:

  • Using publicly hosted copies from CDNs (Community Development Networks) such as Google and Microsoft

  • Downloading and using a local copy

Both methods are widely used today, the trend being more towards using CDNs. CDNs have performance benefit in terms of improving caching and parallelism. However, in applications deployed on the intranet or applications that have limited or no Internet access, it might be better to host a local copy on the web server or the local file system.

But where exactly does jQuery fit in an ASPX form? To answer that, let's take a look at the basic structure of an ASPX page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs" Inherits="Sample" %>
<!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>RECIPE TITLE</title>
    <script src="js/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        /* INCLUDE JQUERY MARKUP HERE */
    </script>
</head>
<body>
    <form id="form1" runat="server">
       <!—-INCLUDE ASPX MARKUP HERE-- >
    </form>
</body>
</html>

From the above sample ASPX form, note the following:

  • The jQuery library is included in the page header using <script> tags as follows:

    <script src="js/jquery-1.4.1.js" type="text/javascript"></script>
  • The actual jQuery magic is applied in another script block in the page header:

    <script type="text/javascript">
            /* INCLUDE JQUERY MARKUP HERE */
        </script>
  • The web form with the required ASPX markup is included in the page body as follows:

    <body>
        <form id="form1" runat="server">
           <!—-INCLUDE ASPX MARKUP HERE-- >
        </form>
    </body>

Note

For the purpose of this book, we have downloaded the uncompressed version of jQuery 1.4.1 on the local system. All recipes and code samples are based on this version of jQuery. The future releases of the library are expected to be compatible backward.

Getting started

Using Visual Studio 2010:

  • Create a new ASP.NET website Chapter1 in Visual Studio 2010 as shown below:

  • Since jQuery is distributed with Visual Studio 2010, the library can be directly included and used on ASPX pages as displayed in the screen below:

Using Visual Studio 2008

Note

To enable jQuery intellisense in Visual Studio 2008, ensure that you have upgraded VS2008 to Service Pack 1 and applied the hotfix KB958502 http://archive.msdn.microsoft.com/KB958502.

Usage of jQuery Library

Create a test form in the project and drag-and-drop the jQuery source file on the form. Visual Studio will automatically add the following code to the ASPX file:

<script src="js/jquery-1.4.1.js" type="text/javascript"></script>

The 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() {
……………….
……………….
});
</ 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.

Now, with this information, let's move on to the recipes where we will solve specific web development problems using jQuery. We have focused on the jQuery scripting required for solving the given problem. The ASP.NET code-behind logic is left to the reader to implement as required.

Note

The recipes in this book have been tested with IE 8, Mozilla Firefox 3.6, and Chrome 9.0. The complete source code for all chapters is included with the book.

When using the provided source code, update the namespace in the Page directive of the ASPX files <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Recipe1.aspx.cs" Inherits="Recipe1" %> to your own local namespaces.

 

Creating default text for TextBoxes


In this recipe, let's see how to create a search box in ASP.NET with some default information text. The text is displayed only when the search box is out of focus.

Getting ready

  1. Add a new web form Recipe1.aspx to the current project.

  2. Add a TextBox field with a Search button to the form as below:

    <form id="form1" runat="server">
        <p></p>
        <div align="center">
           <fieldset style="width:400px;height:80px;">
            <p><asp:TextBox ID="TextBox1" width="200px" CssClass="defaultText" ToolTip="Enter your search keyword here" runat="server"></asp:TextBox>
            <asp:Button ID="btnSubmit" Text="SEARCH" runat="server" /></p>
           </fieldset>
        </div>
        </form>
  3. The CSS class defaultText attached to the TextBox is defined as below:

    .defaultText
        {
          font-style:italic;
          color:#CCCCCC;
        }
  4. Thus on loading, the page displays the search form as shown in the following screen:

We will now use jQuery to display the default text when the search box is out of focus.

How to do it…

  1. In the document.ready() function, retrieve the TextBox control using its ClientID and save in a local variable:

    var searchBox = $('#<%=TextBox1.ClientID%>') ;
  2. On the focus event, check if it contains the default text:

    searchBox.focus( function() {
                    if (searchBox.val() == this.title) {

    Note

    The ToolTip property of the ASP.NET TextBox control is rendered as title at runtime. Thus, the ToolTip text Enter your search keyword here is retrieved using this.title.

  3. If yes, then remove the defaultText css style:

                        searchBox.removeClass("defaultText");
  4. Also clear the search field:

                        searchBox.val("");
                    }
                });
  5. On the blur event, check if the TextBox is empty:

    searchBox.blur( function() {
                    if (searchBox.val() == "") {
  6. If yes, then attach the "defaultText" css style:

                        searchBox.addClass("defaultText");
  7. Add the default information text to the search field:

                        searchBox.val(this.title);
                    }
                });
  8. Call the blur event on page load so that the TextBox is initially out of focus:

    searchBox.blur();
    

Thus, the complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            var searchBox = $('#<%=TextBox1.ClientID%>');
            searchBox.focus(
            function() {
                if (searchBox.val() == this.title) {
                    searchBox.removeClass("defaultText");
                    searchBox.val("");
                }
            });

            searchBox.blur(
            function() {
                if (searchBox.val() == "") {
                    searchBox.addClass("defaultText");
                    searchBox.val(this.title);
                }
            });
            searchBox.blur();
        });
    </script>

Note

ClientID is a unique server control identifier generated by ASP.NET to avoid duplicate IDs when controls are repeated; say, for example, in a Repeater control. It is generated by concatenating the ID of the control with the UniqueID of its parent control. Underscore character (_) is used to separate each part of the generated ID.

How it works…

Run the web form. Initially, the page is displayed with the default text. On focusing on the TextBox, the text disappears and the web user can key in the required search keywords. Note that the text style of the default text and the user input are different.

See also

Disallowing cut/copy/paste operations on a TextBox.

 

Auto focus on the first TextBox and tab on the Enter key


When keying in data in a lengthy form, at times web users prefer to tab to the next box by pressing the Enter key. In this recipe, we will see how we can achieve this tabbing effect.

Getting ready

  1. Create a new web form Recipe2.aspx in the current project.

  2. Add a few TextBox controls to create a simple data entry form to capture users' profile information as follows:

    <form id="form1" runat="server">
        <div align="center">
        <fieldset style="width:400px;height:200px;">
        <table cellpadding="3" cellspacing="3" border="0">
        <tr><td>
        <asp:Label ID="lblName" Text="Name: " runat="server"></asp:Label></td>
        <td><asp:TextBox ID="txtName" Width="200px" runat="server"></asp:TextBox></td></tr>
        <tr><td><asp:Label ID="lblAddress" Text="Address: " runat="server"></asp:Label></td>
        <td><asp:TextBox ID="txtAddress" Width="200px" runat="server"></asp:TextBox></td></tr>
        <tr><td><asp:Label ID="lblContact" Text="Contact Number: " runat="server"></asp:Label></td>
        <td><asp:TextBox ID="txtContact" Width="200px" runat="server"></asp:TextBox></td></tr>
        <tr><td><asp:Label ID="lblEmail" Text="Email: " runat="server"></asp:Label></td>
        <td><asp:TextBox ID="txtEmail" Width="200px" runat="server"></asp:TextBox></td></tr>
        <tr><td></td><td><asp:Button ID="btnSubmit" Text="SUBMIT" runat="server" />
        <asp:Button ID="btnReset" Text="RESET" runat="server" />
        </td></tr>
        </table>
        </fieldset>
        </div>
        </form>
  3. The page displays the form as shown in the following screen:

How to do it…

  1. In the document.ready() function in the jQuery script block, use $('input:text:first') selector to retrieve a handle to the first ASP.NET TextBox. Call the focus event on this TextBox:

    $('input:text:first').focus();

    Note

    The ASP.NET engine renders a TextBox control as <input type=text> HTML element at runtime. Hence, the selector $('input:text') can be used to retrieve TextBox controls. The selector $('input:text:first') retrieves the first TextBox on the form.

  2. Use bind to attach an event handler for "keydown" event on all the TextBoxes in the form:

    $('input:text').bind("keydown", function(e) {
  3. Check if the Enter key is pressed:

    if (e.which == 13) {
  4. If the Enter key is pressed, prevent default form submission:

    e.preventDefault();
  5. Increment the index of the current TextBox by 1 to retrieve the handle to the immediately next TextBox on the form:

    var nextIndex = $('input:text').index(this) + 1;
  6. Focus on the next TextBox:

    $('input:text')[nextIndex].focus();
    }
    });
  7. Add reset functionality to the Reset button by adding a reset function to the form object on its click event:

    $('#btnReset').click(
                     function() {
                         $('form')[0].reset();
                     });

    Note

    The selector $('form')[0] retrieves the first form object on the page.

Thus, the complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            $('input:text:first').focus();
            $('input:text').bind("keydown", function(e) {
                if (e.which == 13) {   //Enter key
                    e.preventDefault(); //to skip default behavior of the enter key
                    var nextIndex = $('input:text').index(this) + 1;
                    $('input:text')[nextIndex].focus();
                }
            });

            $('#btnReset').click(
                 function() {
                     $('form')[0].reset();
                 });

        });
    </script>

How it works…

Run the web form. On loading, the cursor auto focuses on the first TextBox. Subsequently, on pressing the Enter key, we can tab to the remaining TextBoxes.

See also

Selecting text in a TextBox and copying to the clipboard.

 

Disallowing cut/copy/paste operations on a TextBox


In this recipe, let's see how to disable cut/copy/paste operations on an ASP.NET Textbox. When requesting sensitive information from the end user such as passwords, credit card details, and transaction pin numbers used in Internet banking, etc. it is preferred that the web user keys in the characters manually rather than pasting from the clipboard.

Getting ready

  1. Add a new web form Recipe3.aspx to the current project.

  2. Create a simple password change form:

    <form id="form1" runat="server">
        <div align="center">
        <fieldset style="width:400px;height:180px;">
        <table cellpadding="3" cellspacing="3" border="0">
        <tr><td colspan="2" class="header">CHANGE PASSWORD</td></tr>
        <tr><td> <asp:Label id="lblCurrentPwd" Text="Current Password: " runat="server"/></td>
        <td> <asp:TextBox ID="txtCurrentPwd" Width="200px" runat="server" TextMode="Password"></asp:TextBox></td></tr>
        <tr><td><asp:Label id="lblNewPwd" Text="New Password:" runat="server"/></td>
        <td><asp:TextBox ID="txtNewPwd" Width="200px" runat="server" TextMode="Password"></asp:TextBox></td></tr>
        <tr><td><label id="lblConfirmNewPwd" runat="server">Confirm New Password:</label></td>
        <td><asp:TextBox ID="txtConfirmNewPwd" Width="200px" runat="server" TextMode="Password"></asp:TextBox></td></tr>
        <tr><td></td><td><asp:Button ID="btnSubmit" runat="server" Text="SUBMIT" />
        <asp:Button ID="btnReset" runat="server" Text="RESET" /></td></tr>
        </table>
        </fieldset>
        </div>
        </form>
  3. The page displays the form as shown in the screen below:

How to do it…

  1. In the document.ready() function in the jQuery script block, use bind to attach the required event handler for cut, copy, and paste events for the New Password TextBox:

    $('#<%=txtNewPwd.ClientID%>').bind('cut copy paste', function(e) {
  2. Override the default cut/copy/paste behavior:

    e.preventDefault();
  3. Display an information message:

    alert("Cut / Copy / Paste disabled in this textbox");
    });
  4. Repeat the above for the Confirm New Password TextBox:

    $('#<%=txtConfirmNewPwd.ClientID%>').bind('cut copy paste', function(e) {
                    e.preventDefault();
                    alert("Cut / Copy / Paste disabled in this textbox too!");
                });

    Note

    Some browsers by default do not allow copy and cut events in a password field. Hence, in such cases, the jQuery function will not be invoked when these events are raised.

Thus, the complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            $('#<%=txtNewPwd.ClientID%>').bind('cut copy paste', function(e) {
                e.preventDefault();
                alert("Cut / Copy / Paste disabled in this textbox");
            });
            $('#<%=txtConfirmNewPwd.ClientID%>').bind('cut copy paste', function(e) {
                e.preventDefault();
                alert("Cut / Copy / Paste disabled in this textbox too!");
            });
        });
    </script>

How it works…

Run the web page. Try cut/copy/paste operations on the New Password and Confirm New Password fields. The page will throw the information message as shown in the screen below:

See also

Creating default text for TextBoxes

 

Highlighting text in a TextBox and copying to the clipboard


In this recipe, we will see how to highlight text in a multiline TextBox control and copy to the clipboard.

Note

Due to the limitation of the jQuery clipboard plugin, this recipe is applicable to IE browsers only.

Getting ready

  1. Create a new web form Recipe4.aspx to the current project.

  2. Add a multiline TextBox with a hyperlink control to the form as shown below:

    <form id="form1" runat="server">
        <div align="center">
           <fieldset style="width:400px;height:300px;">
           <p>Please enter your comments here:</p>
            <asp:TextBox ID="TextBox1" TextMode="MultiLine" Rows="5" Width="300" Height="200" runat="server"></asp:TextBox>
           <br />
           <asp:HyperLink ID="lnkHighlight" Text="Click here to copy!" runat="server"></asp:HyperLink>
        </fieldset>
        </div>
        </form>
  3. The page displays the form as shown in the following screen:

  4. Add css style for highlighted text using ::selection CSS3 selector:

    ::selection
        {
          background:#0000FF;
        }
  5. Add the following css style for the hyperlink:

    a
        {
          cursor:hand;
          color:#0000FF;
        }
  6. Download the jQuery clipboard plugin from http://plugins.jquery.com/project/clipboard.

  7. Include the clipboard plugin on the page along with the jQuery library:

    <script src="js/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="js/jquery.clipboard.js" type="text/javascript"></script>

How to do it…

  1. In the document.ready() function, use the clipboardReady() function of the plugin:

    $.clipboardReady(function() {
  2. Trigger the copy to clipboard action on the click event of the hyperlink:

    $("a").click(function() {
  3. Highlight the text in the TextBox Control:

    $('#<%=TextBox1.ClientID%>').select();
  4. Copy the contents of the TextBox into the clipboard using the clipboard plugin:

    $.clipboard($('#<%=TextBox1.ClientID%>').val()); 
    });
            });

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
        $.clipboardReady(function() {
            $("a").click(function() {
                $('#<%=TextBox1.ClientID%>').select();
                $.clipboard($('#<%=TextBox1.ClientID%>').val());
                });
        });

        }); 
    </script>

How it works…

Run the web page. Enter some text in the multiline TextBox field and click the hyperlink. The text will be highlighted as shown below:

Launch any text editor and press Ctrl+V to paste the text copied from the TextBox.

There's more…

To implement this functionality in non-IE browsers, an alternative to the clipboard plugin such as Zero Clip Board can be used. Zero Clip Board actually uses a flash file and a JavaScript interface. More information on Zero Clip Board can be found at http://code.google.com/p/zeroclipboard/.

See also

Auto focus on the first TextBox and tab on the Enter key.

 

Displaying selected items of a CheckBoxList


In this recipe, we will retrieve the selected items of an ASP.NET CheckBoxList.

Getting ready

  1. Create a new form Recipe5.aspx in the current project. Add a CheckBoxList control to the form. Also add a div area to display the selected items of the CheckBoxList at runtime:

    <form id="form1" runat="server">
         <div align="left">
            <fieldset style="width:400px;height:150px;">
           <p>Different types of packages available:</p>
            <asp:CheckBoxList ID="CheckBoxList1" runat="server">
            <asp:ListItem Text="Standard" Value="1"></asp:ListItem>
            <asp:ListItem Text="Silver" Value="2"></asp:ListItem>
            <asp:ListItem Text="Gold" Value="3"></asp:ListItem>
            <asp:ListItem Text="Premier" Value="4"></asp:ListItem>
            </asp:CheckBoxList>
            </fieldset>
            <br />
            <div id="message"></div>
        </div>
        </form>
  2. The page will display the CheckBoxList as shown below:

How to do it…

  1. In the document.ready() function, define the click function of the CheckBoxList:

    $('#<%=CheckBoxList1.ClientID%>').click(function() {
  2. Create a local string variable and initialize to an empty string:

    var str = "";
  3. Apply a jQuery selector to retrieve the checked boxes and apply the each function to each element returned:

    $('#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked').each(function() {

    Note

    Note that at runtime, the CheckBoxList control is rendered as a container table <table id="CheckBoxList1"> and each of the ListItems are rendered as <input type="checkbox">.

  4. Retrieve the text of the selected CheckBox and append to the local string:

    str = str + " " + $(this).next().text();

    Note

    Each of the checkbox elements is rendered as a <input type="checkbox"> and <label> pair. The label holds the text of the element. Hence, when retrieving the description of the element, we have used $(this).next().text(), where $(this) refers to the current checkbox element and next() refers to the consecutive <label> element.

  5. After the execution of the each() function, display the local string in the div area 'message':

    $('#message').text(str);
    });

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            $('#<%=CheckBoxList1.ClientID%>').click(
                function() {
                    var str = "";
                    $('#<%=CheckBoxList1.ClientID%> input[type=checkbox]:checked').each(function() {
                        str = str + " " + $(this).next().text();
                    });
                    $('#message').text(str);
                });
        });
    </script>

How it works…

Run the page. Select the required checkboxes. The page will display the text of the selected checkboxes as follows:

See also

Selecting/deselecting all items in ASP.NET CheckBoxList

 

Selecting/deselecting all items in CheckBoxList


In this recipe, we will see how to select/deselect all items in an ASP.NET CheckBoxList using a Select All CheckBox Control.

Getting ready

  1. Create a new web form Recipe6.aspx in the current project.

  2. Add a CheckBoxList to the form as well as a Select All CheckBox control on the form:

    <form id="form1" runat="server">
        <div align="left">
           <fieldset style="width:400px;height:170px;">
           <p>Different types of packages available:</p>
        <asp:CheckBox ID="chkSelectAll" runat="server" Text="Select All" />
        <asp:CheckBoxList ID="chkList" runat="server">
            <asp:ListItem Text="Standard" Value="1"></asp:ListItem>
            <asp:ListItem Text="Silver" Value="2"></asp:ListItem>
            <asp:ListItem Text="Gold" Value="3"></asp:ListItem>
            <asp:ListItem Text="Premier" Value="4"></asp:ListItem>
        </asp:CheckBoxList>
        </fieldset>
        </div>
        </form>
  3. The page will display the form as shown in the screen below:

How to do it…

  1. In the document.ready() function in the jQuery script block, add the required handler for the click event of the Select All CheckBox:

    $('#chkSelectAll').click(function() {
    
  2. Use the jQuery selector to retrieve all checkboxes from the CheckBoxList and toggle the 'checked' attribute:

    $("#<%=chkList.ClientID%> input[type='checkbox']").attr('checked', $('#chkSelectAll').is(':checked'));
    }

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            $('#chkSelectAll').click(function() {
            $("#<%=chkList.ClientID%> input[type='checkbox']").attr('checked', $('#chkSelectAll').is(':checked'));
           }
     );
        });
    </script>

How it works…

Run the web page. Now select/deselect the Select All CheckBox. You will notice that the elements in the CheckBoxList are checked/unchecked based on the CheckBox control.

See also

Displaying selected items of a CheckBoxList

 

Getting selected text and value from DropDownList


In this recipe, we will retrieve the Text/Value pair of an ASP.NET DropDownList using jQuery.

Getting ready

  1. Create a new web form Recipe7.aspx in the current project.

  2. Add a DropDownList to the form. Include a div area to the form to display the selected text from the DropDownList:

        <form id="form1" runat="server">
        <div align="center">
           <fieldset style="width:400px;height:80px;">
           <p>Different types of packages available:</p>
        <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Text="--Please Select--" Value=""></asp:ListItem>
        <asp:ListItem Text="Standard" Value="1"></asp:ListItem>
        <asp:ListItem Text="Silver" Value="2"></asp:ListItem>
        <asp:ListItem Text="Gold" Value="3"></asp:ListItem>
        <asp:ListItem Text="Platinum" Value="4"></asp:ListItem>
        </asp:DropDownList>
        </fieldset>
        </div>
        <br />
        <div align="center" id="message"></div>
        </form>
  3. The page displays the DropDownList as shown below:

How to do it…

  1. In the document.ready() function in the jQuery script block, use bind() to attach a handler to the keyup and change events:

    $('select[id$=<%=DropDownList1.ClientID%>]').bind("keyup change", function() {
  2. Check if the selected value of the DropDownList is empty:

    if ($(this).val() != "")
  3. Retrieve the Text/Value pair and display in the div area 'message':

    $('#message').text("Text: " + $(this).find(":selected").text()
                        + ' Value: ' + $(this).val());
  4. If, however, the DropDownList is empty, clear the div area:

    else
    
    $('#message').text(""); 
    });

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
        $('select[id$=<%=DropDownList1.ClientID%>]').bind("keyup change", function() {
            if ($(this).val() != "")
                $('#message').text("Text: " + $(this).find(":selected").text()
                    + ' Value: ' + $(this).val());
            else
                $('#message').text("");        
            });
        });
    </script>

How it works…

Run the web form. Select any item from the DropDownList. The Text/Value pair will display below the control as follows:

See also

Appending items at runtime to an ASP.NET DropDownList.

 

Appending items at runtime to a DropDownList


In web applications, there is often a need to populate a DropDownList dynamically based on the events triggered on other controls on the page. In this recipe, we will see how to create a cascading dropdown where the contents of the second DropDownList are populated based on the selected elements of the first DropDownList.

Getting ready

  1. Create a new web form Recipe8.aspx in the current project.

  2. Drag-and-drop two DropDownList from the ToolBox on the form. Populate the first DropDownList as shown below:

        <form id="form1" runat="server">
        <div align="left">
           <fieldset style="width:350px;height:150px;">
           <div id="contentArea">
           <p>Select the author as required:</p>
           <table cellpadding="0" cellspacing="0" border="0">
           <tr><td>&nbsp;</td>
           <td>
            <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value="" Text="--Please Select--"></asp:ListItem>
            <asp:ListItem Value="MA" Text="Mitch Albom"></asp:ListItem>
            <asp:ListItem Value="PC" Text="Paulo Coelho"></asp:ListItem>
            <asp:ListItem Value="JA" Text="Jane Austen"></asp:ListItem>
            </asp:DropDownList>
            </td></tr>
            <tr><td colspan="2">&nbsp;</td></tr>
            <tr><td>&nbsp;</td>
            <td>
            <asp:DropDownList ID="DropDownList2" runat="server">
            <asp:ListItem Value="" Text="--Please Select--"></asp:ListItem>
            </asp:DropDownList>
            </td></tr>
            </table>
            </div>
        </fieldset>
        </div>
        </form>
  3. The page displays the controls as shown in the screen below:

How to do it…

  1. In the document.ready() function in the jQuery script block, attach the handler for the "change" event in the first DropDownList using bind():

    $("select[id$=DropDownList1]").bind("change", function() {
  • Clear the second DropDownList:

    $("select[id$=DropDownList2] option").remove();
  • Append a default item in the second DropDownList:

    $("select[id$=DropDownList2]").append("<option value=''>--Please Select--</option>");
  • Check the selected value of the first DropDownList and populate the required data in the second DropDownList:

    if ($(this).val() == "MA") {
                  
    $("select[id$=DropDownList2]").append("<option value='MA1'>Have a Little Faith</option>");
                        $("select[id$=DropDownList2]").append("<option value='MA2'>Tuesdays with Morrie</option>");
                        $("select[id$=DropDownList2]").append("<option value='MA3'>The Five People You Meet in Heaven</option>");
                                   }
                    if ($(this).val() == "PC") {
    
    $("select[id$=DropDownList2]").append("<option value='PC1'>The Alchemist</option>");
                        $("select[id$=DropDownList2]").append("<option value='PC2'>By the River Piedra I Sat Down and Wept</option>");
                        $("select[id$=DropDownList2]").append("<option value='PC3'>The Pilgrimage</option>");
                    }
                    if ($(this).val() == "JA") {
    
    $("select[id$=DropDownList2]").append("<option value='JA1'>Pride and Prejudice</option>");
                        $("select[id$=DropDownList2]").append("<option value='JA2'>Emma</option>");
                        $("select[id$=DropDownList2]").append("<option value='JA3'>Mansfield Park</option>");
                    }
    });

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
        $("select[id$=DropDownList1]").bind("change", function() {
        $("select[id$=DropDownList2] option").remove();
        $("select[id$=DropDownList2]").append("<option value=''>--Please Select--</option>");
                if ($(this).val() == "MA") {
                    
                    $("select[id$=DropDownList2]").append("<option value='MA1'>Have a Little Faith</option>");
                    $("select[id$=DropDownList2]").append("<option value='MA2'>Tuesdays with Morrie</option>");
                    $("select[id$=DropDownList2]").append("<option value='MA3'>The Five People You Meet in Heaven</option>");
                                    }
                if ($(this).val() == "PC") {

                    $("select[id$=DropDownList2]").append("<option value='PC1'>The Alchemist</option>");
                    $("select[id$=DropDownList2]").append("<option value='PC2'>By the River Piedra I Sat Down and Wept</option>");
                    $("select[id$=DropDownList2]").append("<option value='PC3'>The Pilgrimage</option>");
                }
                if ($(this).val() == "JA") {

                    $("select[id$=DropDownList2]").append("<option value='JA1'>Pride and Prejudice</option>");
                    $("select[id$=DropDownList2]").append("<option value='JA2'>Emma</option>");
                    $("select[id$=DropDownList2]").append("<option value='JA3'>Mansfield Park</option>");
                }
            });
        });
    </script>

How it works…

Run the web page. Select any item from the first DropDownList. On "change" event, the jQuery script checks for the value of the selected element and accordingly populates the second DropDownList as shown below:

There's more...

An alternative way of appending items to the DropDownList is as follows:

$("select[id$=DropDownList2]").append($("<option></option>").val("MA3").html("The Five People You Meet in Heaven")); 

See also

Getting selected text and value from ASP.NET DropDownList

 

Creating 'Back to Top' ASP.NET hyperlink


In this recipe, we will create 'Back to Top' ASP.NET links to scroll up to the top of the page. These links are useful when the user needs to scroll the page in case the content is more than one screenful.

Getting ready

  1. Create a new web form Recipe9.aspx in the current project. Add a few div areas with some text content in the form. Also add hyperlinks below each div area as below:

    <form id="form1" runat="server">
        <div>
            <asp:HyperLink ID="Top" runat="server"></asp:HyperLink>
            <div style="width:300px;border:solid;">
            Content 1
            <br />
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </div>
            <asp:HyperLink ID="HyperLink1" runat="server" CssClass="backtotoplink"></asp:HyperLink>
            <div style="width:300px;border:solid;">
            Content 2
            <br />
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </div>
            <asp:HyperLink ID="HyperLink2" runat="server" CssClass="backtotoplink"></asp:HyperLink>
            <div style="width:300px;border:solid;">
            Content 3
            <br />
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </div>
            <asp:HyperLink ID="HyperLink3" runat="server" CssClass="backtotoplink"></asp:HyperLink>
        </div>
        </form>
  2. Define the css style for the hyperlinks as below:

    .backtotoplink
        {
         color:#00FF00;
         cursor:hand;
        }
  3. The page displays the content as shown below:

How to do it…

  1. In the document.ready() function in the jQuery script block, add the innerHTML attribute to the hyperlink:

    $(".backtotoplink").attr("innerHTML", "Back to Top");
  2. Add the title attribute:

    $(".backtotoplink").attr("title", "Back to Top");
  3. Add the href attribute:

    $(".backtotoplink").attr("href", "#Top");

    Note

    ASP.NET Hyperlinks are rendered as <a> tags on the web page. By manipulating the href attribute of anchor tags via jQuery, we can set the ASP.NET hyperlink to point to the top of the page.

The complete jQuery solution is as follows:

<script type="text/javascript">
        $(document).ready(function() {
            $(".backtotoplink").attr("innerHTML", "Back to Top");
            $(".backtotoplink").attr("title", "Back to Top");
            $(".backtotoplink").attr("href", "#Top");
        });
    </script>

How it works…

Run the web page. Scroll the page to view the contents. To go back to the top of the page, click on any of the 'Back to Top' links.

See also

Updating URL of ASP.NET hyperlink at runtime

 

Updating URL of ASP.NET hyperlink at runtime


In this recipe, we will update the target URL of an ASP.NET hyperlink control dynamically based on events triggered by other controls.

Getting ready

  1. Create a new web form Recipe10.aspx in the current project. Add an ASP.NET hyperlink control on the page. Also add a RadioButtonList to the form as follows:

        <form id="form1" runat="server">
        <div align="left">
           <fieldset style="width:300px;height:200px;">
           <table cellpadding="0" cellspacing="0" border="0">
           <tr><td width="10px"></td>
           <td>
           <p>Get your news updates here:</p>
            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
            <asp:ListItem Text="CNN" Value="http://www.cnn.com"></asp:ListItem>
            <asp:ListItem Text="BBC" Value="http://www.bbc.co.uk"></asp:ListItem>
            <asp:ListItem Text="Channel News Asia" Value="http://www.channelnewsasia.com"></asp:ListItem>
            </asp:RadioButtonList>
            <br />
            <asp:HyperLink ID="HyperLink1" runat="server">Click here!</asp:HyperLink>
           </td></tr>
           </table>      
        </fieldset>
        </div>
        </form>
  2. The page will display the content as shown in the screen below:

How to do it…

  • In the document.ready() function, use the bind() function to add the handler for the "change" event of the RadioButtonList:

    $("input[type=radio]").bind("change", function() {

    Note

    The ASP.NET RadioButtonList control is rendered as <input type=radio> HTML element at runtime. Hence, the jQuery selector $("input[type=radio]") can be used to retrieve the RadioButtonList.

  • Set the "href" value of the Hyperlink control to the value of the selected radio button:

    $("a").attr("href",$(this).val());
    });

The complete jQuery solution is as shown below:

<script type="text/javascript">
        $(document).ready(function() {
            $("input[type=radio]").bind("change", function() {
                $("a").attr("href",$(this).val());
            });
        });
    </script>

How it works…

Run the web page. Select any required option of the RadioButtonList. The URL of the Click here! hyperlink will update as per your selection.

There's more...

In addition to the bind() function, jQuery also provides live() function to tie events to controls. So, the same recipe, can be implemented using live() as follows:

$("input[type=radio]").live("change", function() {
                $("a").attr("href",$(this).val());
            });

Note

The live() function attaches event handlers to elements that match the selector now and in the future. The bind() function, on the other hand, only attaches event handlers to controls that are added when the DOM is initially loaded.

Thus, bind() is suited for pages with static controls while live() is suited for pages with dynamic controls.

See also

Creating 'Back to Top' ASP.NET hyperlink.

About the Author
  • Sonal Aneel Allana

    Sonal Aneel Allana works as a sessional lecturer at the Singapore campus of the University of Newcastle and the University of Hertfordshire. Her teaching areas include degree level courses in e-learning, intelligent systems, robotics, operating systems, and programming in C/C++, .NET, Java, and Android. She is keenly interested in JavaScript frameworks, such as Bootstrap, Node.js, and AngularJS. She has worked in the IT industry for over 10 years in various positions, such as an application developer, project leader, and trainer. She holds a master's degree in computing from the National University of Singapore and a bachelor's degree in computer engineering from the University of Mumbai. She is certified in security technology and computational neuroscience. She is also the author of the first edition of ASP.NET jQuery Cookbook.

    Browse publications by this author
Latest Reviews (1 reviews total)
ASP.NET jQuery Cookbook
Unlock this book and the full library FREE for 7 days
Start now