proseidon
proseidon

Reputation: 2305

What's the smartest way to select specific table elements in javascript?

I've got a table with hidden rows on it, like such

 -visible-
 -invisible-
 -visible-
 -invisible-

When I click on a table row, I want it to show the invisible row. Currently I have that using this function:

var grid = $('#BillabilityResults');
$(".tbl tr:has(td)").click(
         function () {
             $(grid.rows[$(this).index()+1]).toggle();
         }

However, this table also hides the visible rows if I click on one of the (now visible) hidden rows. I'd like the click function to only work on the specific visible rows. Currently all my invisible rows have the class "even" so I figured I could limit the click based on that. However, I can't seem to find the syntax to explain that to my function. How would I go about doing that? And, more importantly, is there a better way to approach this?

Upvotes: 1

Views: 111

Answers (4)

Diogo Schneider
Diogo Schneider

Reputation: 349

I guess you could check for even/odd rows with the modulus operator before calling your toggling code:

function() { // your anonymous function
    if (rowNumber % 2 == 0) { // only even rows get through here
        // toggle code here
    }
}

I hope it helps.

Upvotes: 1

Lowkase
Lowkase

Reputation: 5699

Use the NOT function to disregard the EVEN tr elements:

http://jsfiddle.net/7AHmh/

<table class="tbl">
<tr><td>one</td></tr>
<tr class="even" style="display:none"><td>two</td></tr>
<tr><td>three</td></tr>
<tr class="even" style="display:none"><td>four</td></tr>
</table>​

$(".tbl tr:has(td)").not("tr.even").click(function() {

    alert("Click triggered.");

    $(this).next("tr").show(); 

});

Upvotes: 1

Evan
Evan

Reputation: 6115

var grid = $('#BillabilityResults');
$(".tbl tr:visible").click(
         function () {
             $(this).next('tr').toggle();
});

Upvotes: 1

Daniel Aranda
Daniel Aranda

Reputation: 6552

Use next:

$(".tbl tr:has(td)").click(
  function () {
    $(this).next().toggle();
  } 
);

And also if you have specific selector for odd or even:

$(".tbl tr.odd").click(
  function () {
    $(this).next().toggle();
  } 
);

But I think that the major help with my answer is to use next() that get you the next row, instead of the index process that you were doing.

Upvotes: 2

Related Questions