0

I have this segment of code here

<table>
    <thead>
        <th>Title One</th>
        <th>Title Two</th>
        <th>Title Three</th>
    </thead>
    <tbody>
        <?php foreach ($foos as $foo): ?>
            <tr>
                <td id="x"><?php echo $foo->bar1; ?></td>
                <td id="y"><?php echo $foo->bar2; ?></td>
                <td id="z"><?php echo $foo->bar3; ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<script type="text/javascript">
    $('#x').on('click', function(){
        console.log($(this).html());
    });
</script>

Suppose I have 10 rows of data there, how will I be able to reference the exact element I have clicked? For example row number 5, how will jQuery know that I have clicked row 5? I can't go writing <td id="x1">,<td id="x2">,<td id="x3">,<td id="x4"> because I can be having a thousand records.

Any help will be appreciated.

1
  • 1
    $(this) will hold reference to the clicked element. I may misunderstood your question. Could you please be more specific? Commented May 6, 2015 at 15:49

5 Answers 5

3

You can use closest('tr') to find the nearest parent tr element, then index() to get the row number. Try this:

$('td').click(function() {
    var $tr = $(this).closest('tr');
    var rowIndex = $tr.index();
});

Example fiddle

Also note that you should remove the id attribute from the td elements in your PHP loop, otherwise you will duplicate them, which is invalid and may lead to JS or rendering issues.

Sign up to request clarification or add additional context in comments.

Comments

2
$('table').on('click', 'td', function() {
    var rowNumber = $(this).closest('tr').index() + 1;
    var content = $(this).html();
    console.log(rowNumber);
    console.log(content);
});

You do not need to know via some sort of identification which you have clicked as jQuery is aware of the element you clicked in relation to the overall DOM.

You do need to add 1 to the row number variable as the index starts counting at 0.

EXAMPLE

5 Comments

I think we can assume the OP will know how to deal with 0 indexed rows. I don't think they literally meant "if I click the fifth row I want a 5". It is more likely they just want access to the row, so index() will be redundant on all the answers :)
Perhaps @TrueBlueAussie, but it cannot hurt to state it.
Agreed it is worth pointing out (have updated own answer to do that too), but no point compensating for it :)
Very nice :) and thank you for using this.id initially haha
I do what I can @SterlingArcher - save for reading too quickly :)
2

Use .index() if you need to know the position of the element.

$('td').on('click',function()
{
    console.log($(this).closest('tr').index())
})

Otherwise $(this) will be the element itself.

2 Comments

This one does not target the row index. There are no LI in the example
Yeah - sorry - that was my bad. I just made a quick fiddle to get the index. I can fix it
1

Assuming you listen for clicks on the TDs, you can get the closest ancestor TR and simply see what it's index position is within its parent with index():

$('table td').on('click', function(){
    console.log($(this).closest('tr').index());
});

If the rows/TDs are added dynamically, use a delegated version of on instead:

$('table').on('click', 'td' function(){
    console.log($(this).closest('tr').index());
});

This one applies the selector only when the event occurs.

Notes:

  • index returns values starting at 0.
  • You probably do not actually care about the index value itself, but just the closest('tr') in order to do other operations.

Update:

if you want a row id in the table, apply that to the TR element so you get

<tr data-parent_id="myidhere">

and access with

$('table td').on('click', function(){
    var id = $(this).closest('tr').data('parent_id');
});

3 Comments

Under your notes, note number 2, I want to get the id (from the database) for that particular row. Where do I place my data-parent_id attribute?
@Richie: Updated. Let me know if you need more detail.
... oh it's so lonely at the bottom here... with an early answer... but no fan club :>
0

If you need the row number, you could use the index function. The easiest way to do this is to change the click handler (assuming you want to get the index of any td in your tr that is clicked). You don't even need to put ids on your TDs anymore:

<tr class = 'clickiness'>
    <td id="x"><?php echo $foo->bar1; ?></td>
    <td id="y"><?php echo $foo->bar2; ?></td>
    <td id="z"><?php echo $foo->bar3; ?></td>
</tr>
<script>
$( document ).ready( function() {
    $( '.clickiness' ).click( function( event ) {
        var $tds = $( this ).children();
        var $clickedTD = $( event.target );
        var clickedIndex = $clickedTD.index( $tds );    // the zero-based index
    });
});
</script>

What I'm doing here is setting setting the click handler to the TR, so when anything inside that TR is clicked, the function will run, and then I'm using the event variable to get the actual element that was clicked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.