Monday, January 2, 2012

Toggling Checkboxes in a Table with JQuery

I had a small problem tonight that was fun to solve. I have a table and in the first column of each row there is a checkbox. I want the checkbox to toggle when the row is clicked. This is easy to accomplish with some JQuery.

Here is a snippet of my HTML table:

Name Size Modified
Folder 1.0 KB Dec. 28, 2011, 3:41 p.m.
This is a new folder for the new project 53 bytes Jan. 3, 2012, 5:05 a.m.
ETC

And here is the accompanying JQuery:

$("tr").click(function(){
    var checkbox = $(this).children().children("input");
    checkbox.attr("checked", !checkbox.attr("checked"));
  });

The code finds the correct checkbox using the $(this) property provided by the event and the children() selector. Two children calls are necessary, first for the children of the TR, then for the children of the TD, this last one is specified to be the "input" child. The toggle is achieved by setting the "checked" attribute of the checkbox to the opposite of whatever it is currently set at, !$(checkbox).attr("checked");. Simple, love it!

4 comments:

  1. Great post and a very helpful tutorial .
    Thanks a lot for sharing this with us,it helped us a lot.
    JQuery training in Bangalore

    ReplyDelete
  2. Casino: Why is gambling the most dangerous of all
    A casino gambling addict is simply gambling the most dangerous of gri-go.com all herzamanindir.com/ other people. A gambler's life is not just about the outcome 1xbet 먹튀 of apr casino an worrione action,

    ReplyDelete
  3. Thanks for sharing such an useful and informative blog post.
    also, join Java course in Pune

    ReplyDelete
  4. Thank you for sharing such a really admire your post. Your post is great!

    ReplyDelete