rc3.org

Strong opinions, weakly held

jQuery evangelism

For the past few weeks, I’ve been completely obsessed with jQuery, one of the many fine JavaScript UI libraries that are competing for your attention these days. I can’t really tell you whether jQuery is better than any of the other libraries, but I can say that it’s infinitely better than writing your own JavaScript by hand, and that it’s very approachable. You can start doing really powerful things with jQuery with a very small time investment, especially if you already know a little JavaScript and you understand CSS selectors.

Rather than provide a full primer on how jQuery works, I thought I’d provide an example of the kinds of thing jQuery makes easier. Here’s some real JavaScript code:

$(document).ready(function(event) {
    $("#sameAsPhysical").change(function(event) {
        if (event.target.checked) {
            $("#physical input").each(function() {
                $("#billing input[name='" + $(this).attr("name").replace(/physical/, "billing") + "']").val($(this).val());
            });
        }
    });
});

Here’s how the code works. I have a form that has two fieldset elements. One contains the fields for the physical address for a business, the other contains the fields for the billing address. Because the fields are in the same form, they need different names, so all of the physical address fields begin with physical and all the fields associated with the billing address start with billing.

The first thing I do in this code is bind a handler to the onChange event for a checkbox with the ID sameAsPhysical. Like every other JavaScript library, jQuery provides a facility for binding events to elements at page load time, allowing you to follow the tenets of unobtrusive JavaScript. In this case, I bind an anonymous function to $(document).ready(), which fires when all of the page content has loaded. I do all of my other event binding inside that anonymous function.

My goal here is to bind a function to the onChange event associated with my checkbox. Here’s where the “query” part of jQuery comes into play. To get a reference to the checkbox, I just use $("#sameAsPhysical"). As you can probably tell, that query selects an element with the ID sameAsPhysical, just like it would in a style sheet.

jQuery makes event binding simple by adding methods to selectors for each of the events that you can associate with them. So to bind a function to the onChange event, you just call change() on the results of your query. If the query returned a list of elements, the same function would be bound to all of the elements in the query results, as you’ll see in a moment.

Inside the event handler function, I need to check to see whether the checkbox (which has the label “Same as physical address”) is checked, and if it is, I copy all of the values from the “physical” fields to the “billing” fields.

jQuery helpfully passes in the event being captured to my function, so to check the state of the checkbox, I use the expression event.target.checked. If the box is checked, I copy the values. Now for the cool part.

First I query for $("#physical input"), which returns a list of all of the input elements inside an element with the ID physical. I call the each method on the results, which calls the function passed to it as an argument on each of the elements returned. Inside the function I’m going to copy the value in the field passed to each‘s callback to the value of the corresponding field in the other fieldset, containing the billing address fields.

Let’s look at this line of code:

$("#billing input[name='" + $(this).attr("name").replace(/physical/, "billing") + "']").val($(this).val());

First I grab a reference to the corresponding billing field for the physical field being processed. (Remember we’re inside a loop that’s iterating over the fields in the physical section of the form.)

jQuery goes beyond CSS selectors and provides some XPath-like features. In this case, I write a jQuery that looks like this #billing input[name='billing_address']. That returns any input fields in the billing section that have a name attribute set to billing_address. jQuery selectors are ridiculously powerful.

To create the billing_address name, I use a JavaScript expression: $(this).attr("name").replace(/physical/, "billing"). The trick here is that $(this) is a reference to the current element being passed into the callback function associated with the each method. So I replace “physical” in the name of that element with “billing” to grab the billing field that corresponds with this.

jQuery adds a convenience method to elements that are form fields, called val(). If you call it without an argument, it returns the value in that form field. If you pass it an argument, it sets the value of the field to the argument. So .val($(this).val()) sets the value of the field I looked up (using the name I constructed) to the value of this, which again is the form field passed in by each.

Needless to say this one line of code accomplishes a whole lot, and it’s par for the course with jQuery. You can get an amazing amount done with only a couple of lines of code. Here’s another much simpler example:

$("p.note").prepend('<span class="red">Note</span>: ');

This is a way to fake the ability to use the :before CSS pseudo-selector and the content property. It finds all of the paragraphs with the class note on the page and prepends my text label before the content in the tag.

These are all things you can do with JavaScript alone or with any of the libraries out there, but what I like about jQuery is that it allows you to accomplish these kinds of things with very little code, using a query language that’s easy for humans to comprehend. It doesn’t matter how powerful a tool is if you don’t actually use it, and I find jQuery to be a tool that’s easy to find ways to use. I highly recommend checking it out.

4 Comments

  1. We’ve been using jQuery for a while now on the “backstage” webpages at Pandora.com (i.e. profile page, artist/album/track detail pages) and it’s great. It makes DHTML and Ajax soooo much easier!

    The nice thing too is that it’s a very active project, and they are always adding new things and making it faster (yet, somehow keeping it fairly simple to use).

  2. Yes, jQuery is fantastic. I’d simplify your first example to something like this, though:

    $(function() {
      $("#sameAsPhysical").change(function() {
        if (this.checked) {
          $("#physical input").each(function() {
            var self = $(this);
            $("#billing input[name='" +
                self.attr("name").replace(/physical/, "billing") +
              "']").val(self.val());
          });
        }
      });
    });

    Not tested in any way, but the point is to not do $(this) too many times and to utilize the shortcuts available in jQuery, like $(function() {}) instead of $(document).ready(function() {}) and this instead of event.target.

    With the jQuery printf plugin, you can rewrite the string concatenation bit to something like this:

    $($.sprintf("#billing input[name='%s']",
      self.attr("name").replace(/physical/, "billing")
    )).val(self.val());

  3. Great comment. Thanks for the illumination.

  4. If there are any select menu element values to copy, you can add them to the Xpath selector:

    $("#shipping_fieldset input, #shipping_fieldset select").each(function() {
        var elem = $(this);
        $("#billing_fieldset #"+ 
            elem.attr("id").replace(/shipping/, "billing")).val(elem.val());
    });
    

Leave a Reply

Your email address will not be published.

*

© 2016 rc3.org

Theme by Anders NorenUp ↑