Nuno_147
Nuno_147

Reputation: 2913

Figure out the element in the a table (using class) when using jquery

I am using a table grid in my HTML and while clicking on a specific col in each row, I dynamically create an additional row using <tr>. The additional row is used to submit data to the server and remove it after submit. Now I would like in addition to this that the row number of the table will be sent to the server as well.

The table is changed dynamically as I am adding rows for editing. I thought about fixing this by giving each <tr> a class named task_entry and by counting the number of .task_entry elements I will be able to figure out which row I am in. However I cannot get this to work. I tried to use $(".task_entry").index(this) but it returns -1.

Can anyone help?

Upvotes: 0

Views: 54

Answers (3)

isotrope
isotrope

Reputation: 1847

Don't use .live() as it's deprecated.

Please try playing this fiddle: http://jsfiddle.net/mB49c/1/

Based on the structure in it:

$(document).ready(function() {

    $('table').on('click', 'td', function() {

        //count the row. 0 based. If you want to start at 1, add 1
        var my_row = $(this).parent('tr').index('table tr');

        $('table').append('<tr class="saving"><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td><td>Col 5</td></tr>');


        alert('You clicked on row ' + my_row + ' run some code.. for instance AJAX');

        //If using AJAX, add this as a Success callback
        $('.saving').remove();
    });
});

Upvotes: 1

jammon
jammon

Reputation: 3464

Please check what this is in your case. Could it be the col, you are clicking on? Then $(".task_entry").index($(this).closest('tr')) should do the trick.

Upvotes: 0

Ali Alnoaimi
Ali Alnoaimi

Reputation: 2317

$(function() {
  $("table td").click(function() {
    var this_is = $(this).attr("id");
    var this_val = $(this).html();

    alert(this_val)

  });
});

Upvotes: 0

Related Questions