views:

2497

answers:

2

Hello All,

I'm currently using jQuery and would like some help on iterating through all "checked" checkboxes and remove a class (called "new_message") of the parent table row.

I've got a basic concept, but I can't quite figure the entire thing out.

Here is what I am currently using:

$("#unread_button").click(function (event) {
event.preventDefault;
$(":checkbox:checked").each( 
function() 
{ 
    if (this.checked) 
    { 
  var divs = $.makeArray($(this).parents("tr").attr("id"));
  }
$(divs).each(
 function(int)
  {
   $(this).removeClass("new_message");
  }
 );
  });  
});

Eventually, this will be updating a database as well, so if the code can be tailored to accomodate both, that'd be great.

Any guidance is much appreciated!

+1  A: 
$("input:checked").each(function() {
    $(this).removeClass("new_message");
}

will remove the relevant class from the checkboxes themselves, so

$(this).parent....

should work depending on what your HTML looks like

Neil Middleton
+5  A: 

I think this will work:

$('input:checkbox:checked').parents('tr').removeClass('new_message');

Or if it's only the direct TR parent you want to match, then this:

$('input:checkbox:checked').closest('tr').removeClass('new_message');

jQuery does all the looping for you so you should have to have all the each()es.

Once you use the ':checked' selector, you should have to recheck if the item is checked. This should limit your selector results to only checked items.

MacAnthony
I would use .closest as parents gets all ancestors then filters - slower
redsquare
I thought about that but the OP didn't specify if it was only the first level TR parent or if there were multiple. And since it sounded like the current selector was working, didn't want to change it.
MacAnthony
That was it. Thanks. I've also used .closest, which works just as well.
Change `:checkbox:checked` to `input:checkbox:checked`, there's plenty of performance to be gained here. The first selector is equal to `*:checkbox:checked` and jQuery is much faster at filtering by tag name (since it uses native functions for tag names, while the other filters use custom functions.)
Blixt
Thanks Blixt, will do.