jQuery problem solving

By | April 6, 2007

A guy on the jQuery mailing list asked how to achieve a goal. He had a table with checkboxes in  them.  He wanted the last checkbox to change the values of all the ones in that row.  The first answer came from Roman Weich which was:

$(‘input.rowChecker’).click(function(){
  $(this).parent().siblings(‘.updateItems’).find(‘input[@type=checkbox]’).attr(‘checked’,this.checked);
});

I loook at it and thought.  Hmm, it assumes classes on the td’s and on the last input.  There must be a way to do this without classes.  It took me a little while to troubleshoot.  I had a little help from Ben Nadel, but eventually figured out this:

$("table tr td:last-child input").click(function(){
     $("../../td input[@type=checkbox]", this).attr("checked", this.checked);
    }
  )

Now, it’s not much smaller, but the HTML is much simpler.  No classes.  This is also my first working xPath (notice the ../../).  It’s also my first try at last-child.  I felt joy that this worked.  Without jQuery this would be a total pain the butt with lots of loops and if statements.  Yuck.  This way the html is clean and the script is small and reusable.

It might seem insignificant.  But this is just a small example of how jQuery has made web development easier for people like me.

Leave a Reply