Mike Sav
Mike Sav

Reputation: 15291

How can I tell which row has been clicked?

Afternoon,

say I have a table like so

<table id="foo">
  <tr><td><!-- label --><!-- textbox --></td><tr>
  <tr><td><!-- label --><!-- textbox --></td><tr>
  <tr><td><!-- label is bar --><!-- textbox --></td><tr>
  <tr><td><!-- label --><!-- textbox --></td><tr>
  <tr><td><!-- label --><!-- textbox --></td><tr>
</table>

how could I in JQuery determine the index of the row that has had it's textbox amended (on blur)? So if a user adds a value to the textbox on the third row ("label is bar") I could alert the row index (in this case 2)?

I'm assuming I'd get the table id, perform an each on the tr, then find the text box using children and when that child has it's onblur event activated we then use parent to output the index?

Any ideas?

Thanks

Upvotes: 1

Views: 949

Answers (5)

Enki
Enki

Reputation: 573

By amended you mean onchange ?

If yes you could do :

$("#foo input").change(function(){
  alert($('#foo td').index($(this).parent()));
});

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

$("input[type=text]").blur(function() {
    alert($(this).closest("tr").index());
});

This attaches the blur event to all input elements with type="text". You might want to narrow down that selector to only select inputs inside your table.

In the event handler function, it gets the closest tr (that is, the first ancestor element of this which is a tr, and gets the index of that).

Here's an example fiddle showing it in action.

As noted in another answer, you may actually be looking for the change event, rather than the blur event as you say in your question. The change event will fire when the value of the input actually changes, as opposed to whenever it loses focus. If that's the case, simply change the word blur to change.

Upvotes: 3

laurac
laurac

Reputation: 429

$('#foo tr').click(function(){
   console.log($(this).index());
})

Upvotes: 1

gred
gred

Reputation: 537

You should add a handler for the proper event, e.g. blur or whatever you want, for the input field and inside the handler find the row(tr) using the parent (like you said). e.g.

$('.testFieldsClass').blur(function() {
    //first parent is td, second is tr take it and do whatever!
    var currentTR = $(this).parent().parent();

    //... do something in curretnTR
});

NOTE: IN MY EXAMPLE I assume that all text fields have a class named testFieldsClass, easier for the selector. ALSO, in my example I only catch the blur event for the text fields.

Upvotes: 0

Phil
Phil

Reputation: 11175

Misread the question, editing it!

$('#foo tr td').click(function() {
    alert($(this).index());
});

Upvotes: 3

Related Questions