tags:

views:

31

answers:

2

Here is my Jquery

$th.each(function(idx) {
      var notSelected = $(this).text();
      if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) {

      if (idx < 10)
      {
         $(this).show();
         // and show its corresponding td
         $td.eq(idx).show();
      }
      }
    }); 

It is part of a tableFilter type function for a HTML table. However I want it to only display only 2 of the results. I tried instantiating some kind of index counter but I was unsuccessful. Any help or thoughts would be appreciated.

+1  A: 
var index = 0;
$th.each(function(idx) {
      var notSelected = $(this).text();
      if ((notSelected.indexOf(to) != -1) || (notSelected.indexOf(from) != -1)) {

      if (idx < 10 && index < 2)
      {
         $(this).show();
         // and show its corresponding td
         $td.eq(idx).show();
         index = index + 1;
      }
      }
    }); 
derek
or you could use index += 1; as that last line in the inner if block.
Ken Ray
A: 

This is more efficient than the accepted answer and won't pollute your namespace.

(function(index){
    $th.each(function(idx) {
        if(idx < 10){
            var self = $(this),
                notSelected = self.text();
            if ( notSelected.indexOf(to) > -1 || notSelected.indexOf(from) > -1 ) 
                self.show();
                // and show its corresponding td
                $td.eq(idx).show();
                if(++index===2){
                    //break the loop
                    return false;
                }
            }
        }
    });
}(0));
David Murdoch