views:

96

answers:

4

I have jQuery code which looks something like this

on Button1 Click

$('table.result_grid tbody tr')
    .filter(function() {
        var chkbox = $(this).find(':checkbox')[0];
        return !chkbox.checked;
    })
    .show();

on Button2 Click

 $('table.result_grid tbody tr')
     .filter(function() {
         var chkbox = $(this).find(':checkbox')[0];
         return !chkbox.checked;
     })
     .hide();

on both the click it searches for the same tr.
Is there a way to optimize the above code?
Is there a way I can store the above tr in a variable blah and then say blah.hide() or blah.show().

+1  A: 

Yes. Use

var blah = $('table.result_grid tbody tr') .filter(function() { var chkbox = $(this).find(':checkbox')[0]; return !chkbox.checked; });
Button1.onClick=function(){blah.hide()};
Button2.onClick=function(){blah.show()};
Veton
This does not seem to work
Balaji
This works if i write hide and show in a single function.My button1 and button2 call separate functions.Could you please suggest?
Balaji
@Balaji: `Button1.onClick=function(){blah.hide()};` could be replaced with something more jQuery-ish. Also, you could put your handler before or after `blah.hide()`. Or, you could pass `blah` to your handler.
geowa4
A: 

Something like this:

$('.button1, .button2').click(function() {
  $('table.result_grid tbody tr').
    filter(function() {
      var chkbox = $(this).find(':checkbox')[0];
      return !chkbox.checked;
    }).
    [$(this).is('.button1') ? 'hide' : 'show']();
});
searlea
A: 

You should be able to select unchecked checkboxes using the :not pseudoclass and an attribute selector.

$('table.result_grid tbody tr input:not([checked])').show();
Øystein Riiser Gundersen
A: 

First off, let the selectors do the work. You will likely not do better than the efficiency of jQuery. This will get all the rows that contain checkboxes:

$('table.result_grid tbody tr:has(input:checkbox)')

Next, choose more efficient selectors. This is a good idea for your CSS too. Here I am adding ">" to denote the right is a direct descendant of the left:

$('table.result_grid > tbody > tr:has(td > input:checkbox)')

Finally, save the collection of returned rows:

var cached_rows = $('table.result_grid > tbody > tr:has(td > input:checkbox)')

Make sure that the cached_rows variable is kept in a scope that is accessible to each of you handlers. If you do not want or cannot put those variables in that scope, then be careful passing the reference around.

geowa4