简体   繁体   中英

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

Misread the question, editing it!

$('#foo tr td').click(function() {
    alert($(this).index());
});
$("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 .

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

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

$('.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.

By amended you mean onchange ?

If yes you could do :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM