Published: 25 Mar 2009
By: Brian Mains

An example-driven tutorial on the JQuery library by Brian Mains.

Contents [hide]

Introduction

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. Let’s see how.

Accessing a Range of Values

JQuery makes it easy to access form data. For example, suppose the following markup is the target for JQuery.

Listing 1: Table Markup

Parsing a table in JQuery is easy, and there can be a couple of approaches to extract the information. Let’s assume that the goal is to get the rows of the table’s body only, and not the header.

Listing 2: Accessing the rows of the body

The latter option notes a hierarchical structure using the > designation. This signals a hierarchy of elements to drill down through. Alternatively, the children method parses children of the table as a collection. The script in Listing 2 accesses all of the tables within the page, so this approach may not be the most practical for an application. The reason is that the layout for the table often uses tables to layout the data, and parsing all tables isn’t always desirable. Maybe it is; this simply requires examining a site’s layout structure.

Alternatively, a better approach would be to give the table an ID and change the scripts to the following:

Listing 3: Accessing the rows of a specific table

Taking this further, if the script needs to access a specific value within the table, there are a couple of alternative approaches. Let’s assume the goal on this section is to sum the balances column in the table, which happens to be the last cell in each table row.

Listing 4: Sum the results of the balance column

The each method comes in handy here; this method fires the inline event handler once for each table cell in the result set. The :last designation filters the table row’s cells to return only one cell instead of four. Within this event handler, the this keyword refers to the table cell being processed.

So in the end, the each event handler fires three times, and adds the values stored within the Balance column and adds it to sumTotal. Another approach to summing results could be to use classes.

Listing 5: Using Classes to Parse Ranges of Values

The marker class is simply a way for JQuery to identify the fields to total. The .marker notation signals to JQuery to target any element bearing the marker CSS class. The marker class is simply used to target the element. Each element returned is summed and the value is appended to the total.

The reasoning for appending the new value to the total when processing each HTML element is because the function does not run synchronously. Rather, it runs asynchronously and thus the total value isn’t calculated until all of the events fire. Placing the total assignment to the label after the each statement would assign a zero value.

Accessing Nearby Elements

Sometimes you may be within the DOM tree accessing a specific element, but really need an element nearby. It depends where in relation to you that you need to go. Suppose you were working with the situation in Listing 6. Imagine that this markup gets rendered by a data-bound control like the repeater.

Listing 6: Example Markup

Let’s look at a couple of scenarios related to this. The first scenario is accessing siblings. Suppose that the hidden field at the end stores the key to an item that will be uploaded to the server using AJAX. So the application needs to process the textbox and the key, and process them separately. If an event handler was attached to the button click events on client-side (there isn’t one defined above but let’s assume there is), JQuery allows us to access each sibling like so:

Listing 7: Accessing the TextBox and Hidden Field

The siblings method returns a collection of related siblings to the button, and thus these siblings are filtered out by the expression the method allows passed into it. If, for whatever reason, the situation was different, and the application had a reference to the textbox, JQuery can retrieve the hidden field in several ways.

Listing 8: Accessing the hidden field from the textbox reference

While not the most practical in this scenario, I’ve used this approach in other applications. Essentially, the + symbol means that the second control ID, class, or tag name is next to the first, and thus because we have a reference to the textbox, JQuery uses the ID of the textbox (whether statically or dynamically) to find the next sibling.

At this point, the JQuery queries work one element at a time because in the situation where the user clicks a button, only one action needs to be performed (only one record gets updated to the database as a result of a save). Therefore, we only need to access one textbox/hidden field at a time. In a bulk-save scenario, we may want to do something more like the following.

Listing 9: Bulk Save to Web Service

The children method accesses the children of the element with an ID of parent, which is a parent span tag. Each child gets parsed individually. Each DIV element has the information from its textbox and hidden field extracted, and passed along to a web service that saves the information.

In looking at this example from a reverse angle, you can see that the parsing works the opposite way. From the button level, the button can parse upward using the parent or parent methods as in Listing 10. Assume that the button variable is a reference to the actual button element within one of the parent DIV’s.

Listing 10: Accessing parent information

So the parent/parents method can access a single or multiple parents. Using JQuery filters can limit the result-set that’s found, which is designated by the :first statement. JQuery has a lot of helpful filters which I wrote about in my article on this site called “Introduction to JQuery.”

Conclusion

JQuery is a powerful language, and hopefully this article shows you why.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Brian Mains

Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Animating a Web Form using ASP.NET AJAX
In this article you will learn how to animate a webform using asp.net ajax.
Jquery Ajax
JQuery makes communicating with the server very, very easy. JQuery uses get(), getJSON(), and post(...
jQuery in Action 2nd edition: Queuing functions for execution
This article is taken from the book jQuery in Action, second edition. This segment shows how you can...
Test120Jan
This is my custom article
jQuery Deferred Objects Promise Callbacks
jQuery Deferred/Promise objects untangle spaghetti-like asynchronous code.

You might also be interested in the following related blog posts


Shows how to create a jQuery-enabled WCF service to retrieve stock quotes and display via jQuery Templates read more
Assembly-Free jQuery in SharePoint Sites Using the SmartTools jQueryLoader read more
Take Two: A jQuery WCF/ASMX ServiceProxy Client read more
WebGrid 3.1 is now public and supporting JQuery UI CSS Framework read more
Getting and setting max zIndex with jQuery read more
Speaking at the Portland Area .NET User Group on Tuesday Sept 1st read more
Script# (Script Sharp) writing javascript in C# read more
CodeDigest.Com - Articles,FAQs, Codes, News - Aug,2009 read more
AJAX Logging with Exponential Backoff read more
Custom Events in jQuery read more
Top
 
 
 

Please login to rate or to leave a comment.

Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.